问题
for quite a few hours now, I've been struggling with an issue regarding list views in java in a practice to-do app that I'm trying to make. I have a list view on my main activity and after changing from that activity and back to it, the list view is gone. I googled and saw people changing things and saving instances and tried to implement it with no success, however, that might be because I'm extremely new to java. Here is the code:
public class MainActivity extends AppCompatActivity {
private ArrayList items;
private ArrayAdapter itemsAdapter;
private ListView lvItems;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
lvItems = (ListView) findViewById(R.id.lvItems);
items = new ArrayList();
itemsAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, items);
lvItems.setAdapter(itemsAdapter);
items.add("Test");
setupListViewListener();
}
// Attaches a long click listener to the listview
private void setupListViewListener() {
lvItems.setOnItemLongClickListener(
new AdapterView.OnItemLongClickListener() {
@Override
public boolean onItemLongClick(AdapterView<?> adapter,
View item, int pos, long id) {
// Remove the item within array at position
items.remove(pos);
// Refresh the adapter
itemsAdapter.notifyDataSetChanged();
// Return true consumes the long click event (marks it handled)
return true;
}
});}
public void onChangeView(View v) {
setContentView(R.layout.activity_create);
}
public void onConfirmItem(View v) {
EditText etNewItem = (EditText) findViewById(R.id.etNewItem);
String itemText = etNewItem.getText().toString();
itemsAdapter.add(itemText);
etNewItem.setText("");
setContentView(R.layout.activity_main);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu items for use in the action bar
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.menu_main, menu);
return super.onCreateOptionsMenu(menu);
}
回答1:
You are using setContentView() at multiple places, but you are not setting the adapter therein. You can call setContentView any time you are running on the event (UI) thread. Be aware that when you do, any fields you initialized by calling findViewById
will need to be reset.
回答2:
Instead of this :
lvItems.setAdapter(itemsAdapter);
items.add("Test");
Do this :
items.add("Test");
lvItems.setAdapter(itemsAdapter);
you are setting an empty adapter & then filling array
And the other problem is pointed by @Skynet thanks for that
来源:https://stackoverflow.com/questions/32971035/list-view-dissapears-after-changing-activities