1

在下面的代碼片段中有一條註釋行。當我取消註釋該行時,則LinearLayout的內容不會顯示在TableRow中。如果不設置LayoutParams,該行將顯示兩個文本。我不明白這種行爲。我知道,我可以通過xml文件包括複雜的看法,但我寧願明白什麼是錯與此代碼:應用LayoutParams隱藏視圖

TableLayout tableLayout = (TableLayout) findViewById(R.id.table); 

    TableRow tableRow = new TableRow(this); 
    tableRow.setLayoutParams(new TableRow.LayoutParams(TableRow.LayoutParams.MATCH_PARENT, TableRow.LayoutParams.MATCH_PARENT)); 

    LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(TableRow.LayoutParams.MATCH_PARENT, TableRow.LayoutParams.MATCH_PARENT); 

    LinearLayout linearLayout = new LinearLayout(this); 
    linearLayout.setOrientation(LinearLayout.HORIZONTAL); 
    // when I comment out this line, the row only shows the second text. 
    // linearLayout.setLayoutParams(layoutParams); 

    TextView textLabel = new TextView(this); 
    textLabel.setText("inside linear layout"); 
    linearLayout.addView(textLabel); 

    TextView message = new TextView(this); 
    message.setText("inside tablerow"); 

    tableRow.addView(linearLayout); 
    tableRow.addView(message); 

    tableLayout.addView(tableRow); 
+0

也許你忘記添加布局params用於在文本視圖?我認爲TextView的寬度和高度現在是0dp,並且linearLayout具有match_parent參數,因此您可以看到空視圖 –

+0

當我使用'textLabel.setHeight(20); textLabel.setWidth(20)'它也沒有顯示 – shaft

+0

嘗試更改linearLayout的layoutParams源 新LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT,LinearLayout.LayoutParams.MATCH_PARENT); –

回答

1

假設的問題是一樣的東西「什麼這個問題如何解決呢? 「,這裏是我的答案:

當設置LayoutParamsView,這些PARAMS將這個View的父母來是View適當佈局。所以你的情況你做了什麼是以下幾點:

 


    LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(...); 
    linearLayout.setLayoutParams(layoutParams); 
    tableRow.addView(linearLayout); 

 

現在,tableRow是混亂的,因爲它需要以適當佈局視圖TableRow.LayoutParams,卻突然發現了一些其他的佈局PARAMS。然而,如果你明確指定參數而不是(即當linearLayout.setLayoutParams()被註釋掉),則默認佈局參數would be generated

 


    @Override 
    protected LinearLayout.LayoutParams generateDefaultLayoutParams() { 
     return new LayoutParams(); // this is TableRow.LayoutParams 
    } 

 

所以,而不是創建LinearLayout.LayoutParams,創建TableRow.LayoutParams

 


    TableRow.LayoutParams layoutParams = new TableRow.LayoutParams(...); 
    linearLayout.setLayoutParams(layoutParams); 
    tableRow.addView(linearLayout); 

 
+0

謝謝你的解釋。它有訣竅。 – shaft