2014-02-22 191 views
0

比方說,我有一個LinearLayout,我想添加兩個視圖。第一個包含editText,另一個包含listview。我一直在嘗試java中的代碼如下:AddView error,只顯示第一個元素

EditText inputViaText; 
    ListView historyInput; 
    protected static LinearLayout askTextLayout = null; 

    askTextLayout = new LinearLayout(this); 
    askTextLayout.setVisibility(LinearLayout.VISIBLE); 
    askTextLayout.setOrientation(LinearLayout.HORIZONTAL); 

    inputViaText = new EditText(this); 
    LinearLayout.LayoutParams askTextParams = new LinearLayout.LayoutParams(LayoutParams.FILL_PARENT,LayoutParams.WRAP_CONTENT); 

    historyInput = new ListView(this); 
    LinearLayout.LayoutParams historyInputParams = new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT,70); 

    askTextLayout.addView(historyInput,historyInputParams); 
    askTextLayout.addView(inputViaText,askTextParams); 

    FrameLayout.LayoutParams frameAskTextParams = new FrameLayout.LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT, Gravity.BOTTOM); 
    setContentView(R.layout.activity_main); 
    addContentView(askTextLayout, frameAskTextParams); 

但是,它只是顯示我添加的第一個。所以當我編碼如下:

 askTextLayout.addView(historyInput,historyInputParams); 
    askTextLayout.addView(inputViaText,askTextParams); 

它只是顯示listView。當我編碼如下:

 askTextLayout.addView(inputViaText,askTextParams); 
    askTextLayout.addView(historyInput,historyInputParams); 

它只是顯示edittext。任何人都可以幫助我?

回答

1

嘗試在你的活動

context = this; 

     setContentView(R.layout.activity_main); 
     container = (LinearLayout) findViewById(R.id.Linear); 
     LinearLayout linearLayout = new LinearLayout(context); 
     linearLayout.setWeightSum(100); 
     ListView v1 = new ListView(context); 
     v1.setBackgroundColor(Color.CYAN); 
     LinearLayout.LayoutParams p1 = new LinearLayout.LayoutParams(0, 
       50); 
     p1.weight = 90; 
     v1.setLayoutParams(p1); 
     EditText v2 = new EditText(context); 
     v2.setText("Hello"); 
     v2.setBackgroundColor(Color.WHITE); 
     LinearLayout.LayoutParams p2 = new LinearLayout.LayoutParams(0, 
       50); 
     p2.weight = 10; 
     v2.setLayoutParams(p2); 
     linearLayout.addView(v1, p1); 
     linearLayout.addView(v2, p2); 
     View view = new View(MainActivity.this); 

     LayoutParams lp = new LayoutParams(LayoutParams.MATCH_PARENT, 
       1); 
     view.setLayoutParams(lp); 
     view.setBackgroundColor(Color.BLACK); 
     container.addView(linearLayout); 
     container.addView(view); 


Write this in activity_main: 

<LinearLayout 
     android:id="@+id/Linear" 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content" > 
    </LinearLayout> 
+0

的onCreate方法,其中該線ID來自這個代碼? 「container =(LinearLayout)findViewById(R.id.Linear);」 –

+0

我編輯了我的答案,檢查了這一點。 – 2014-02-24 05:01:18