2012-10-24 131 views
2

我是android開發中的新成員..我正在使用fragment。我現在面臨的問題是 - 我無法在fragment中動態添加視圖。當我嘗試這樣做時,我得到了一個NullPointerException ...我的代碼段如下:動態地在片段中添加textview

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> 

的片段是tabgroup的成員屬於片段活動。我在代碼片段中做錯了什麼T'任何形式的幫助是appreciated.Thanks提前...

+0

我試着用它id..But這種方法也參考了的LinearLayout不成功... – SALEH

+0

這段代碼片段在哪裏? –

+0

你在哪裏得到NPE? (exact line) – sandrstar

回答

3

試試這個片段上的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; 

}

+0

中的片段你試過嗎?它工作嗎? –