mardi 12 mai 2015

Android: Dynamically created table row is being deleted on screen rotate

From what I have read online, any dynamically created views should be saved when the android screen is rotated as long as those views are given an arbitrary id.

I am running into a problem, however, where any dynamically created table row that is created is deleted when the screen changes orientation from portrait to landscape or vice versa.

I have a TableLayout defined in my main activity's fragment which is modified after an activity where the user defines the data for a new table row finishes.

So far that part works fine.

The table stores an item and a corresponding location. itemInsertResponse is called by onActivityResult, which appends the new row returned by createItemRow to the existing table.

public void itemInsertResponse(Intent data) {
    String item = data.getStringExtra("item");
    String location = data.getStringExtra("location");

    TableLayout itemCatalog = (TableLayout) findViewById(R.id.tbl_catalog);
    itemCatalog.addView(createItemRow(item, location), new TableLayout.LayoutParams(TableLayout.LayoutParams.MATCH_PARENT, TableLayout.LayoutParams.MATCH_PARENT));


}

public TableRow createItemRow(String item, String location) {
    TableRow itemRow = new TableRow(this);
    itemRow.setLayoutParams(new TableLayout.LayoutParams(TableLayout.LayoutParams.MATCH_PARENT, TableLayout.LayoutParams.MATCH_PARENT));
    TextView itemText = new TextView(this);
    TextView locationText = new TextView(this);
    itemText.setText(item);
    itemText.setId(3);
    locationText.setId(4);

    locationText.setText(location);

    itemRow.addView(itemText);
    itemRow.addView(locationText);


    //setPadding appears to take values in px, need to conver to dp
    int padding_in_dp = 5;  // 6 dps
    final float scale = getResources().getDisplayMetrics().density;
    int padding_in_px = (int) (padding_in_dp * scale + 0.5f);
    itemRow.setPadding(padding_in_px, padding_in_px, padding_in_px, padding_in_px);
    itemRow.setId(9001);

    return itemRow;

}

I set id values for the table row and the text views which, from what I have read, should mean that the default implementation of OnSavedInstanceState saves them.

Is this some kind of bug, or do I actually need to manually save the newly created rows in OnSavedInstanceState in order to maintain the state of the table? If I do need to override that method, how do I save every dynamically created row?

The best solution I can think of is to store a global ArrayList of arrays containing the two strings for each row and then recreate every row in OnCreate using that ArrayList--but that's clearly very inefficient.

Aucun commentaire:

Enregistrer un commentaire