2013-05-16 157 views
0

我想單擊按鈕時動態添加文本視圖。我已經實現了這一點,但添加它時,通過編寫以前的one.Any錯我的代碼?動態添加多個佈局android

imGbtn.setOnClickListener(new OnClickListener() { 

      public void onClick(View v) { 
       int id =0; 
       final String data = textView.getText().toString(); 
       //childHolder.title.setText(data); 
       LinearLayout ll = new LinearLayout(mContext); 
       ll.setOrientation(LinearLayout.VERTICAL); 
       ll.setId(id); 
       tvll.addView(ll); 
       // TextView tv1 = new TextView(mContext); 
       // tv1.setText("Dynamic layouts ftw!"); 
       // ll.addView(tv1); 

       LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT); 
       layoutParams.setMargins(25, 20, 25, 10); 
       TextView tv= new TextView(mContext); 
       tv.setId(id); 
       tv.setText(data); 
       ll.addView(tv,layoutParams); 
       textView.setText(""); 

      } 
     }); 

回答

0

我建議定義LinearLayout在Java佈局xml.Create對象內,然後在LinearLayout中點擊按鈕添加TextView的。

<LinearLayout 
      android:id="@+id/relatedChannels" 
      android:layout_width="wrap_content" 
      android:layout_height="wrap_content" 
      android:orientation="vertical" > 
     </LinearLayout> 

的Java

LinearLayout cat_linear=(LinearLayout) findViewById(R.id.list_Category); 
    TextView tv = new TextView(context); 
    tv.setText(category.get(i).getNAME()); 
    tv[i][i].setLayoutParams(new LinearLayout.LayoutParams(
    LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT, 1f)); 
    cat_linear.addView(tv); 
2

下面的代碼中的LinearLayout的onclick

public class ViewOnClick extends Activity { 
    LinearLayout.LayoutParams layoutParams; 
    LinearLayout ll; 
    static int i; 
    /** Called when the activity is first created. */ 
    @Override 
    public void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.main); 
     Button b = (Button)findViewById(R.id.Button01); 

     b.setOnClickListener(new OnClickListener(){ 

      @Override 
      public void onClick(View v) { 


    LinearLayout ll = new LinearLayout(mContext); 
       ll.setOrientation(LinearLayout.VERTICAL); 
       ll.setId(id); 
LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT); 
       layoutParams.setMargins(25, 20, 25, 10); 
       EditText view = new EditText(ViewOnClick.this);    
       view.setText(++i+" view"); 
       ll.addView(view, layoutParams); 

      }}); 
    } 
} 
添加EDITTEXT