2012-07-10 99 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);