4

私はアンドロイド開発の新人です..フラグメントを使用しています.現在直面している問題は、フラグメントにビューを動的に追加できないことです.これを実行しようとすると、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>

フラグメントは、フラグメント アクティビティに属するタブグループのメンバーです。コード スニペットで何が間違っていますか? どんな種類の助けも大歓迎です。事前に感謝します...

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 に答える