在片段中动态添加textview

时间:2012-10-24 09:29:40

标签: android android-layout view android-fragments

我是android开发的新手。我正在处理片段。我现在面临的问题是 - 我无法在片段中动态添加视图。当我尝试这样做时,我得到了一个nullpointerexception ...我的代码段如下:

final LinearLayout linearLayout = (LinearLayout)inflater.inflate(R.layout.connections_layout, container, false);
EditText editText = new EditText(getActivity());

final int i = 5;
editText.setId(i); //Set id to remove in the future.
editText.setLayoutParams(new LayoutParams(
        LayoutParams.FILL_PARENT,
        LayoutParams.WRAP_CONTENT));
editText.setText("Hello");
Log.d("View","Start");
try{
    linearLayout.addView(editText);
}catch(Exception e){
    e.printStackTrace();
}

connection_layout.xml 文件如下:

<?xml version="1.0" encoding="utf-8"?>
  <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
                      android:id="@+id/connections"
                      android:layout_width="fill_parent"
                      android:layout_height="fill_parent"
                      android:background="#FF0000" >

  </LinearLayout>

该片段是属于片段活动的选项卡组的成员。我的代码片段出错了什么?任何形式的帮助表示赞赏。谢谢你提前......

1 个答案:

答案 0 :(得分:4)

在片段的onCreateView

上试试这个
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

 mContainer = inflater.inflate(R.layout.connections_layout, null);
 LinearLayout linearLayout = mContainer.findViewById(R.id.connections);
 EditText editText = new EditText(getActivity());

 final int i = 5;
 editText.setId(i); //Set id to remove in the future.
 editText.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT,
            LayoutParams.WRAP_CONTENT));
 editText.setText("Hello");
 Log.d("View","Start");
 try{
        linearLayout.addView(editText);
 }catch(Exception e){
        e.printStackTrace();
 }

 return mContainer;

}