2012-07-19 83 views
2

我試圖在按下按鈕時將佈局添加到我的視圖中。佈局中的ID爲2 EditText s被添加到List<EditText>,所以無論添加多少個XML佈局實例,都可以訪問它們。但是,我有麻煩讓這個工作。Android:通過膨脹XML動態添加布局

主要功能建立視圖:

ViewGroup view = null; 
    TextView addressView; 
    Button submit; 
    ImageView addHeader; 

    private int id = 0; 
    private List<EditText> editTexts = new ArrayList<EditText>(); 


    @Override 
    public void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.get); 

     view = (ViewGroup) findViewById(R.id.getLayout); 


     addressView = (TextView) view.findViewById(R.id.getAddress); 
     submit = (Button) view.findViewById(R.id.getSubmit); 
     addHeader = (ImageView) view.findViewById(R.id.getHeaderAdd); 

     addHeader.setOnClickListener(new OnClickListener() { 
      @Override 
      public void onClick(View v) { 
       addHeaderBox(); 
      }   
     }); 

我的功能附加布局:

private void addHeaderBox() {  
    LayoutInflater inflater = (LayoutInflater) this.getSystemService(Context.LAYOUT_INFLATER_SERVICE); 

    inflater.inflate(R.layout.get_param, view, false); 

    EditText nameBox = (EditText) view.findViewById(R.id.getValue); 
    EditText valueBox = (EditText) view.findViewById(R.id.getName); 

    nameBox.setId(id++); 
    valueBox.setId(id++); 

    editTexts.add(nameBox); 
    editTexts.add(valueBox); 
} 

getValuegetName是兩個EditText S在我的佈局ID的(不是主要getLayout )。 96

07-19 10:25:13.088: E/AndroidRuntime(32034): java.lang.NullPointerException 
07-19 10:25:13.088: E/AndroidRuntime(32034): at myapp.httprequest.free.GETActivity.addHeaderBox(GETActivity.java:96) 
07-19 10:25:13.088: E/AndroidRuntime(32034): at myapp.httprequest.free.GETActivity.access$0(GETActivity.java:88) 
07-19 10:25:13.088: E/AndroidRuntime(32034): at myapp.httprequest.free.GETActivity$1.onClick(GETActivity.java:65) 

線是nameBox.setId(id++)

回答

5

嘗試:

....... 
View someView = inflater.inflate(R.layout.get_param, view, false); 

EditText nameBox = (EditText) someView.findViewById(R.id.getValue); 
EditText valueBox = (EditText) someView.findViewById(R.id.getName); 
........ 
+0

,做吧!非常感謝! – 2012-07-19 14:42:13

1
View view = inflater.inflate(R.layout.get_param, view, false); 

充氣膨脹,但膨脹的結果是不分配給任何查看對象。

+0

,當我宣佈了,它被正確初始化:'私人列表 editTexts =新的ArrayList ();' – 2012-07-19 14:39:27