[英]ListView hides after screen rotation
我對如何組織ListView的保存還原過程Activity狀態感到困惑。 我這樣做是為了一個沒有任何問題的TextView。 我找不到一個示例來了解ListView的行為。
我試圖保存ArrayList,保存適配器狀態,然后還原,但沒有任何效果。 休息的東西正常工作。
公共類MainActivity擴展了AppCompatActivity {
private static final int GOODS_REQUEST = 1;
private ListView listView;
private ArrayAdapter<String> adapter;
private ArrayList<String> arrayList;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//creating Array list which will be populate returned Goods
arrayList = new ArrayList<String>();
//creating "Adapter" which behaves as a middleman between the data source and the layout
// retrieves the data and converts each entry into a view that can be added into the layout
adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, arrayList);
listView = findViewById(R.id.list_view_goods);
//Sets the adapter that provides the data and the views to represent the data in this widget.
listView.setAdapter(adapter);
//Restoring Activity instance state
if (savedInstanceState != null){
arrayList = savedInstanceState.getStringArrayList("received_goods");
adapter.notifyDataSetChanged();
}
}
//event handler
public void addGoods(View view) {
Intent openGoodsList = new Intent(this, GoodsList.class);
startActivityForResult(openGoodsList, GOODS_REQUEST);
}
//receiving Goods
@Override
protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == GOODS_REQUEST && resultCode == RESULT_OK && null != data) {
String goods = data.getStringExtra(GoodsList.EXTRA_GOODS);
arrayList.add(goods);
//Notifies the attached observers that the underlying data has been changed and any View reflecting the data set should refresh itself.
// Use the method every time the list is updated.
adapter.notifyDataSetChanged();
}
}
//saving Activity instance state
@Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putStringArrayList("received_goods", arrayList);
}
需要說明ListView在保存-還原過程中的行為或顯示它的示例。
當您調用'savedInstanceState.getStringArrayList(“ received_goods”)'時,您的arrayList實例已更改,現在它與適配器中的數組列表實例不同,您應該這樣做:
if (savedInstanceState != null){
ArrayList<String> tmp= savedInstanceState.getStringArrayList("received_goods");
arrayList.addAll(tmp);
adapter.notifyDataSetChanged();
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.