使用LayoutInflater创建动态视图

Jam*_*ley 1 xml android

我创建了一个xml文件,我希望重复多次并在主视图中填充.我已经读过LayoutInflater是要走的路,但我遇到了让它运行的问题

第一个问题.我创建的xml项目中有许多textview.可以这样做,还是xml只能包含一个textview?

ScrollView mainlayout = (ScrollView) findViewById(R.id.ScrollView1);    
LayoutInflater  inflater = (LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            View view = (View) inflater.inflate(R.layout.sightmarks_item, null);
            TextView textview1 = (TextView) inflater.inflate(R.id.textView1, null);
            EditText editview1 = (EditText) inflater.inflate(R.id.editview1, null);
            EditText editview2= (EditText) inflater.inflate(R.id.editview2, null);
Run Code Online (Sandbox Code Playgroud)

然后我在数组上运行for循环并为上面的每个值设置文本,然后将视图添加到mainlayout视图

目前在膨胀的视图上出错了.我这样做是否正确?

谢谢

Sun*_*hoo 5

您的代码中存在一些问题.获取任何视图的元素使用findViewById方法

ScrollView mainlayout = (ScrollView) findViewById(R.id.ScrollView1);    
LayoutInflater  inflater = (LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View view = (View) inflater.inflate(R.layout.main, null);
TextView textview1 = (TextView) view.findViewById(R.id.textview1);
EditText editview1 = (EditText) view.findViewById(R.id.editview1);
EditText editview2= (EditText) view.findViewById(R.id.editview2);
Run Code Online (Sandbox Code Playgroud)