如何在android中动态创建线性布局添加动态按钮

时间:2015-07-22 07:30:29

标签: android button dynamic textview android-linearlayout

在使用两个动态TextView 1.textView和2.textView_dynamic创建动态线性布局后,我为textView_dynamic编写了一个onclick,以在动态创建的线性布局中添加动态按钮。添加点击视图但按钮不可见后,它会显示空白区域。

以下是代码: -

代码: -

// Parent1 layout
LinearLayout parent1Layout = (LinearLayout)findViewById(R.id.layout1);
LayoutInflater layoutInflater2 = getLayoutInflater();
View view2;
for(int i = 0; i < 2; i++){
// Add the text layout to the parent layout
    view2 = layoutInflater2.inflate(R.layout.text_layout, parent1Layout,false);

    //In order to get the view we have to use the new view with text_layout in  it
    TextView textView = (TextView)view2.findViewById(R.id.text);
    textView.setText("Row 2" + i);

    //Add the text view to the parent layout
    parent1Layout.addView(textView,i);

    final LinearLayout dynamic = new LinearLayout(getApplicationContext());
    dynamic.setLayoutParams(new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT));
    dynamic.setOrientation(LinearLayout.HORIZONTAL);

    // Layout inflater
    LayoutInflater layoutInflater1 = getLayoutInflater();

    final View view1;
    view1 = layoutInflater1.inflate(R.layout.text_layout, dynamic, false);

    TextView textView_dynamic = (TextView)view1.findViewById(R.id.text);
    textView_dynamic.setText("Linear dynamic new dynamic " + i);

    dynamic.addView(textView_dynamic);

    parent1Layout.addView(dynamic, i);

    textView_dynamic.setOnClickListener(new View.OnClickListener() {

    @Override
    public void onClick(View v) {
       // TODO Auto-generated method stub

      Button button2 = new Button(getApplicationContext());
      button2.setText("Dynamic Add");
      button2.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT));

      dynamic.addView(button2);
      j++;

     }});
}

0 个答案:

没有答案