我创建了一个列表视图,允许用户勾选他们已经看到的列表中的电影。唯一的问题是,当我更改活动或关闭应用程序时,它会将列表视图中的所有元素重置为默认值。我想知道是否有一种方法可以使用我当前的代码保存这些更改。保存Android的setOnItemClickListener数据
public class Movies extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_movies);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
ListView moviesListView = (ListView)findViewById(R.id.moviesListView);
final ArrayList<String> topMovies = new ArrayList<String>(asList("The Shawshank Redemption", "The Godfather", "The Godfather: Part 2",
"The Dark Knight", "Pulp Fiction","Schlinder's List","12 Angry Men","The Lord of the Rings: The Return of the King",
"The Good, the Bad and the Ugly","Fight Club","The Lord of the Rings: The Fellowship of the Ring","Star Wars: Episode V - The Empire Strikes Back",
"Forrest Gump","Inception","One Flew Over the Cuckoo's Nest","The Lord of the Rings: The Two Towers","Goodfellas",
"The Matrix","Seven Samurai","Star Wars: Episode IV - A New Hope","City of God","Se7en","The Silence of the Lambs",
"The Usual Suspects","It's a Wonderful Life","Life is Beautiful","Leon: The Professional","Once Upon a Time in the West",
"Spirited Away","Interstellar","Saving Private Ryan","Casablanca","American History X","Psycho","City Lights","Raiders of the Lost Ark",
"Rear Window","The Intouchables","Modern Times","The Green Mile","Terminator 2: Judgement Day","The Pianist","The Departed",
"Whiplash","Back to the Future","Memento","Gladiator","Apocolypse Now","Dr. Strangelove","The Prestige"));
ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, topMovies);
moviesListView.setAdapter(arrayAdapter);
final MediaPlayer mPlayer = MediaPlayer.create(this,R.raw.pindrop);
moviesListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
if(view.getAlpha()==1f) {
mPlayer.start();
Toast.makeText(getApplicationContext(), "You Watched " + topMovies.get(position), Toast.LENGTH_LONG).show();
view.animate().alpha(0.2f);
}
else{
view.animate().alpha(1f);
}
}
});
}
}
您需要保存某些地方(通常在数据库中)这些更改以跟踪电影是否标记为已显示或未显示。 – kevinkl3
在Android上保存数据最简单的方法是使用SharedPreferences。但是如果你有关于数据库的一些知识,你可以使用SQLite。这里有一些链接,让你开始:http://stackoverflow.com/questions/3624280/how-to-use-sharedpreferences-in-android-to-store-fetch-and-edit-values http:// www.androidhive.info/2011/11/android-sqlite-database-tutorial/ –
谢谢你们。共享首选项能够保存列表视图中的所有50行吗? – BelovedAunt