I'm trying to learn how to add a TextView programmatically and I found many answers on this subject. I have the following code working:
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
LinearLayout llCommand1 = (LinearLayout) findViewById(R.id.LL_Main);
llCommand1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
mtAdd_Register();
}
});
}
public void mtAdd_Register(){
View llColumn1 = findViewById(R.id.Column1);
TextView tvData1 = (TextView) getLayoutInflater().inflate(R.layout.tv_red, null);
sData = "user input" //I'll write a method to get user input
tvData1.setText(sData);
tvData1.setLayoutParams(new LinearLayoutCompat.LayoutParams(LinearLayoutCompat.LayoutParams.MATCH_PARENT,30));
((LinearLayout) llColumn1).addView(tvData1);
}
"LL_Main" is an horizontal LinearLayout with 6 child vertical LinearLayouts (Column1 to Column6), and "tv_red" is used to set gravity to "center" and background color to "red" (with a border, from a drawable resource).
This code works, in a certain way, cause when I click on LL_Main at run time I get the TextViews added as expected. For this test a TextView is created only in Column1, but later I'll have an array with id's and a loop to create a TextView for each column.
But what I want is to have those added Textviews in place when I run the app again, I mean, at first my app doesn't have any data to display and my goal is to add and keep a note when the user touches the screen, so the user will see the previous added TextViews everytime he runs the app.
Am I following the right path? Or should I save the user input to a JSON file and retrieve it everytime I run the app? But even if I have to save the user inputs on JSON file, how to keep the TextViews in order to display the saved data?
I just thought: when I fisrt run the app I can get inputs and add, say, 5 TextViews. I save the JSON file and when I run the app again I must check how much data the file has. So my code should add as many TextViews as demanded to display the data retrieved.
Yes?.......
EDIT:
Just to be clearer: say my layout has nothing in it, and my activity_main.xml shows nothing but an empty screen. When the user touches the screen a TextView is added with the text "user input". And that's gonna happen as many times as he touches the screen.
BUT when he closes the app and runs it again.......... all the TextViews are gone. Everytime the user runs the app he sees an empty screen. I need the previous TextViews to be there............