如果我在按钮点击时在同一父母中多次充气视图,我如何知道视图的ID?

时间:2011-12-13 11:44:26

标签: android android-layout android-view

我有一个困难的情况,让我这样说,我希望用户使用我的3个文本字段来设置警报数据,并在填写信息后,我给他一个选项,为此设置另一个警报目的我用一个按钮。我在表布局中有三个表行,这些表行在child.xml文件中定义,并且每个元素都有一个Id集。在我的活动中,我在按钮点击事件上多次膨胀child.xml,并且我能够根据需要成功地多次充气。但我的问题是因为我在运行时多次膨胀相同的xml文件(我不知道多少次),我很困惑,如何从特定文本字段(如TextViews)检索数据并通过因为我需要这么做的唯一身份证。 你是如何去做的?

4 个答案:

答案 0 :(得分:2)

我会以编程方式进行讨论。

当用户请求新警报时,您会膨胀您的xml文件。此时,会在您的活动中保留对夸大视图的引用(在列表或其他类型的集合中)。

因此,当您想要检索数据时,请不要使用findViewById,而只需使用您的参考。

答案 1 :(得分:2)

可能会有所帮助...


            LinearLayout ll=(LinearLayout) findViewById(R.id.i1);   ///main xml file which contains the layout i m inflating
            String str[]={"a","b","c"};
            View vi[]=new View[3];
            LayoutInflater li=(LayoutInflater)this.getSystemService(LAYOUT_INFLATER_SERVICE);
            for(int i=0;i<3;i++){
                  View v=li.inflate(R.layout.addit, null);
                  TextView t=(TextView) v.findViewById(R.id.t1);
                  t.setText(str[i]);
                  ll.addView(v);
                      vi[i]=v;
            }
            TextView t1=new TextView(this);
            TextView t2=new TextView(this);
            TextView t3=new TextView(this);
            TextView r1=(TextView) vi[0].findViewById(R.id.t1);
            TextView r2=(TextView) vi[1].findViewById(R.id.t1);
            TextView r3=(TextView) vi[2].findViewById(R.id.t1);
            t1.setText(r1.getText());
            t2.setText(r2.getText());
            t3.setText(r3.getText());
            ll.addView(t1);
            ll.addView(t2);
            ll.addView(t3);

             setContentView(ll);

我的addit.xml文件包含以下内容:

       <?xml version="1.0" encoding="utf-8"?>
       <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
          android:id="@+id/l2"
          android:layout_width="match_parent"
          android:layout_height="100dp"
          android:orientation="vertical" >

       <TextView
          android:id="@+id/t1"
          android:layout_width="fill_parent"
          android:layout_height="40dp"
          android:text="" />
       </TextView>
       </LinearLayout>

这里我动态添加addit.xml布局3次,其中包含id为t1的textview。 对于每个textview,我从字符串数组str设置一个文本.. 并将每个视图对象v添加到数组以进行引用... 现在,如果我想获取每个textview的文本,我可以使用对数组中存储的视图的引用,并通过id在代码中查找文本视图,以从每个textview获取文本

enter image description here

答案 2 :(得分:1)

请记住每个实例View时获得的inflate()引用。当您需要从中查看文本时,将这些内容投射到TextView

答案 3 :(得分:1)

我将从基本的

开始
<Layout>
<Button1>
</layout>

现在正在进行活动

Button btn;View view1=null;
///Inflate file if view is null
first time when you inflating
view1=inflate
 btn=view1.findViewbyid();

现在假设你已经膨胀了另一个视图,但是view1值没有改变,那么btn将包含该按钮的引用。当它变为可见时。它将像普通按钮一样工作。