屏幕旋转后,ListView隐藏

时间:2019-01-10 13:17:20

标签: android listview rotation onrestoreinstancestate

我对如何组织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在保存-还原过程中的行为或显示它的示例。

1 个答案:

答案 0 :(得分:0)

当您调用'savedInstanceState.getStringArrayList(“ received_goods”)'时,您的arrayList实例已更改,现在它与适配器中的数组列表实例不同,您应该这样做:

if (savedInstanceState != null){
    ArrayList<String> tmp= savedInstanceState.getStringArrayList("received_goods");
    arrayList.addAll(tmp);
    adapter.notifyDataSetChanged();
}