幾個小時後消失,我一直在努力解決一個關於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);
}
是的,這也是一個原因! – Skynet