4

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

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>

该片段是属于片段活动的选项卡组的成员。我在我的代码片段中做错了什么?任何形式的帮助表示赞赏。在此先感谢...

4

1 回答 1

6

在片段上试试这个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;

}

于 2012-10-24T10:12:23.813 回答