2012-04-12 78 views
1

我有一个输入文本的应用程序,用户必须在输入文本旁边插入信息和按钮“+”。 我想让我的表单动态,当用户按下“+”按钮时会动态出现另一个文本输入和旁边的另一个“+”按钮,该过程以相同的方式重复。在活动中添加动态输入文本和按钮android

我创建的XML文件,sample_content:

  <TextView 
       android:layout_width="wrap_content" 
       android:layout_height="wrap_content" 
       android:layout_alignLeft="@+id/attempt" 
       android:layout_alignParentBottom="true" 
       android:text="TextView" /> 

      <Button 
       style="?android:attr/buttonStyleSmall" 
       android:layout_width="36dp" 
       android:layout_height="32dp" 
       android:layout_alignParentRight="true" 
       android:layout_alignParentTop="true" 
       android:layout_marginRight="22dp" 
       android:text="+" /> 

      <EditText 
       android:layout_width="229dp" 
       android:layout_height="wrap_content" 
       android:layout_alignParentTop="true" 
       android:layout_marginRight="14dp" 
       android:layout_toLeftOf="@+id/addKey" 
       android:background="@drawable/inputtext_corner" 
       android:ems="10" 
       android:textSize="18sp" > 

       <requestFocus /> 

      </EditText> 

     </RelativeLayout> 

,并在我的活动,AddDeviceActivity我把:

   inflater = LayoutInflater.from(AddDeviceActivity.this); 
       Button addKey = (Button) findViewById(R.id.addKey); 

       addKey.setOnClickListener(new Button.OnClickListener() { 
        public void onClick(View v) { 
         final RelativeLayout canvas = (RelativeLayout) AddDeviceActivity.this.findViewById(R.id.my_canvas); 
         final View childView = inflater.inflate(R.layout.sample_component, canvas, false); 
         // TODO: Look up the 5 different signatures of the addView method, 
         // and pick that best fits your needs 
         canvas.addView(childView); 
        } 
       }); 

但是这种解决方案不起作用,因为当我添加第一输入文本和第一个按钮,我不知道如何使第二个按钮在我的AddDeviceActivity动态工作

回答

0

Ju ST想知道你是否能做到这一点:

让你的活动实施OnClickListener这种方法添加到您的活动:

public void onClick(View v) { 
    final RelativeLayout canvas = (RelativeLayout) AddDeviceActivity.this.findViewById(R.id.my_canvas); 
    final View childView = inflater.inflate(R.layout.sample_component, canvas, false); 
    canvas.addView(childView); 
    ((Button)childView.findViewById(R.id.addKey)).setOnClickListener(AddDeviceActivity.this); 
} 

,然后改变你的初始代码使用

addKey.setOnClickListener(this); 

,而不是一个匿名内部类。

我没有测试过这个,但是看不出为什么它不起作用。

0

检查出这个,合格null代替canvas对象在inflate()方法

addKey.setOnClickListener(new Button.OnClickListener() { 
         public void onClick(View v) { 
          final RelativeLayout canvas = (RelativeLayout) AddDeviceActivity.this.findViewById(R.id.my_canvas); 
          final View childView = inflater.inflate(R.layout.sample_component, null, false); 
          // TODO: Look up the 5 different signatures of the addView method, 
          // and pick that best fits your needs 
          canvas.addView(childView); 
         } 
        });