I have created a xml file I wish to repeat a number of times and populate within the main view. I have read that LayoutInflater is the way to go but I am having issues getting it to work
first question. the xml item I created has a number of textview within it. Can this be done or can the xml only contain one 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, nu开发者_C百科ll);
EditText editview2= (EditText) inflater.inflate(R.id.editview2, null);
I am then running round a for loop on an array and setting the text for each the values above and then adding the view to the mainlayout view
Currently it is erroring on the inflated view. am I doing this correctly?
Thanks
There is some problem in your code. To get the element of any view use findViewById
method
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);
I don't think you are doing this the right way. First thing to know is that a Scrollview can contain only one element. Do you have a unique LinearLayout or TableLayout within your Scrollview, to encapsulate the textViews after ?
If I were you :
In your XML layout file (i named it "yourfile" here), use a hierarchy such as :
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android" ... />
<LinearLayout ...>
<TextView .../>
<TextView .../>
...
</LinearLayout>
</ScrollView>
Then in your Activity, inflate the scrollview :
ScrollView mScroll = (ScrollView) getLayoutinflater().inflate(R.layout.yourfile, null)
Then to get the TextViews, go through your ScrollView using getChild(). For example to assign "my text" to the first textview, this should work :
( (TextView) ((ViewGroup) mScroll.getChildAt(0)).getChildAt(0)).setText("my text");
To understand : if you want to reach the single LinearLayout you do
mScroll.getChildAt(0)
So to get to the first text view (first child of LinearLayout), you do
mScroll.getChildAt(0).getChildAt(0)
精彩评论