如何以编程方式添加和保留textview?

时间:2016-03-23 01:02:35

标签: android json textview programmatically-created

我试图学习如何以编程方式添加TextView,我在这个主题上找到了很多答案。我有以下代码:

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"是一个水平的LinearLayout,有6个子垂直LinearLayouts(Column1到Column6)," tv_red"用于将重力设置为" center"和背景颜色为"红色" (带有边框,来自可绘制资源)。

这段代码在某种程度上起作用,当我在运行时点击LL_Main时,我得到了按预期添加的TextViews。对于此测试,TextView仅在Column1中创建,但稍后我将拥有一个带有id的数组和一个为每列创建TextView的循环。

但我想要的是在我再次运行应用程序时添加Textviews,我的意思是,首先我的应用程序没有任何数据要显示,我的目标是添加并保留注释用户触摸屏幕,因此用户每次运行应用程序时都会看到之前添加的TextView。

我是否走正确的道路?或者我应该将用户输入保存到JSON文件并在每次运行应用程序时检索它?但即使我必须在JSON文件上保存用户输入,如何保留TextView以显示保存的数据?

我只是想:当我运行应用程序时,我可以获得输入并添加,例如,5个TextViews。我保存了JSON文件,当我再次运行应用程序时,我必须检查文件有多少数据。所以我的代码应该添加尽可能多的TextViews来显示检索到的数据。

是?.......

编辑:

更清楚一点:说我的布局中没有任何内容,而我的activity_main.xml只显示空屏幕。当用户触摸屏幕时,TextView会添加文本"用户输入"。当他触摸屏幕时,这种情况会发生多次。

但当他关闭应用程序并再次运行时..........所有TextView都消失了。每次用户运行应用程序时,他都会看到一个空屏幕。我需要以前的TextViews ............

1 个答案:

答案 0 :(得分:0)

如果您需要存储轻量级消息,请尝试SharePreferences。

相关问题