几个小时以来,我一直在努力解决我正在尝试制作的实践待办事项应用程序中有关 java 中列表视图的问题。我的主要活动有一个列表视图,从该活动更改并返回它后,列表视图消失了。我在谷歌上搜索并看到人们改变事物并保存实例并试图实现它但没有成功,但这可能是因为我对 java 非常陌生。这是代码:
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);
}