My actual app design has much more complex layout involving GridView with custom adapter, ListView etc and I assume same applies to basic TextView and hence sharing just simple code here.
I already gone though long thread at Saving Android Activity state using Save Instance State and learned(some of them might be assumptions) lot of thing about activity life cycle, fragments , pros/cons of both SavedInstanceState , SharedPreferences etc.
But I still couldn't find how to store TextView's DATA and its ATTRIBUTES for ex. BackgroundColor to retains both after app closed,reopened and also when orientation changed. The other thread I mention above suggests of using SharedPreferences for data which lives long even after app exit and onSaveInstanceState,onRestoreInstanceState for temporary data but nothing specifically about saving view's attributes textsize, backgroundcolor etc when apps is closed.
I assume TextView's text is Data and BackgroundColor is state and both SharedPreferences and onSaveInstanceState should be required? I also assume same solution would work for CustomAdapter of GridView and ListView because basically it contains TextView as its element or do I need different approach to save and restore for storing data,attributes of elements(TextView) of GridView?.
Sample code below in which three TextView is created dynamically and added to LinearLayout and on click event of TextView its Text,BackgroundColor will be changed. These both changes should be restore when app is closed and also when orientation changed.
public class MainActivity extends AppCompatActivity{
private static final String TAG = "MainActivity";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
LinearLayout mDynamicLayout = findViewById(R.id.dynnamicLayout);
for( int i = 1; i < 4; i++ ) {
TextView test = (TextView) getLayoutInflater().inflate(R.layout.gv_item_fixedline,mDynamicLayout,false); // Magic!
int newId = View.generateViewId();
test.setId(newId);
test.setText(Integer.toString(i)); // Remove this if you set text in the xml
test.setTextColor(Color.WHITE);
addListeners(test);
mDynamicLayout.addView(test, i-1); // Bang!
}
}
private void addListeners(final TextView test) {
test.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Log.d(TAG, "onClick: clicked");
int val = Integer.parseInt(test.getText().toString());
val++;
test.setText(Integer.toString(val));
test.setBackgroundColor(Color.MAGENTA);
}
});
}
}