2012-07-10 96 views
0

我使用下面的代碼動態添加LinearLayout。試圖動態插入LinearLayout

public void sendMessage02(View view){ 
    view.getId(); 
    EditText editText=(EditText)findViewById(R.id.edit_message); 
    String message=editText.getText().toString(); 

    LinearLayout l=(LinearLayout)findViewById(R.id.layout_odd); 
    TextView text=new TextView(this); 
    text.setText(message); 
    text.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT)); 
    l.addView(text); 

    LinearLayout l2=(LinearLayout)findViewById(R.id.layout01); 
    l2.addView(l); 

} 

當我運行我的應用程序時,它的仿真器顯示錯誤,說應用程序不幸停止。

我在做什麼錯了?是否有任何其他方式動態添加布局。

+0

會需要從logcat登錄才能確定錯誤源。 – Hein 2012-07-10 07:36:17

+0

@ user1509702發佈您的logcat,以便我們可以幫助您。 – 2012-07-10 07:58:41

回答

1

有了這個例子,你並不是想要插入一個LinearLayout。你得到你現有的LinearLayout

LinearLayout l=(LinearLayout)findViewById(R.id.layout_odd); 

的一個參考,並添加一個TextView它

l.addView(text); 

如果你想dinamically添加的LinearLayout,你必須把你的ViewGroup的參考,並附加一個新的LinearLayout到它。

你可以創建你的LinearLayout創建一個全新的實例:

LinearLayout l = new LinearLayout(context); 

或從佈局資源不斷膨脹:

LinearLayour l = getInflater().inflate(R.layout.my_linear_layout); 

,然後將其連接到您的ViewGroup

ViewGroup root = findViewById(R.id.my_view_group); 
root.addView(l);