0

I have a button in my main layout and onClick I'm reusing another xml layout following way:

View view = layoutInflater.inflate(R.layout.single_elemnt,
                            createLayout, false);
createLayout.addView(view, position);
position++;

where single_elemnt is the layout that will be added to the current main layout every time add button(present in main layout) is clicked.

single_elemnt has 2 views: a textview and an edittext. I'm using tv = (TextView) findViewById(R.id.tv); each time add is clicked.

But the problem is tv is always referring to the first textview even though I have placed findViewById code in onClick.

main.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent" >

        <!-- some other views -->

            <Button
                android:id="@+id/add"
                android:layout_width="100dp"
                android:layout_height="wrap_content"
                android:layout_centerHorizontal="true"
                android:layout_centerVertical="true"
                android:gravity="center"
                android:paddingTop="10dp"
                android:text="Add"
                android:textSize="20sp" />

</RelativeLayout>

onClick method in activity

 View view = layoutInflater.inflate(R.layout.single_elemnt,
                                createLayout, false);
    createLayout.addView(view, position);
    position++;
tv = (TextView)profile.findViewById(R.id.tv);
tv.setText("some text");

Am I doing anything wrong here? Any help appreciated.

4

1 回答 1

1

您需要在该特定视图中找到视图,如下所示:

View view = layoutInflater.inflate(R.layout.single_elemnt,
                                createLayout, false);
createLayout.addView(view, position);
tv = (TextView) view.findViewById(R.id.tv);
tv.setText("some text");

position++;
于 2013-04-30T08:02:22.603 回答