標籤:layout ui android 控制項
Android大部分的控制項都會有padding和layout_margin兩個屬性,一般來說它們的區別是:
padding:控制項中的內容離控制項邊緣的距離。
margin: 控制項離它的父控制項邊緣的距離。
今天做了一個由根布局動態載入子布局的實驗,結果發現子布局中的這兩個屬性可以按預期的效果顯示,但是給根布局設定的padding並沒有對被載入的子布局產生效果。
代碼如下:
根布局檔案名稱為activity_main.xml,其xml檔案定義的內容為:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" android:padding="8dp" <!-- 這個布局裡控制項都距離它的邊緣8dp --> tools:context=".MainActivity" ></LinearLayout>
上面這個根布局會添加子布局table_layout.xml中定義的布局,這個xml檔案的定義內容是:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="vertical" > <TextView android:id="@+id/tableLayout_tableName" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_margin="10dp" <!-- 這個控制項離table_layout這個布局的邊緣為10dp --> android:textSize="30sp" /></LinearLayout>
源碼中實現動態載入的程式碼片段:
// 建立用於承載表的布局LinearLayout subLayout = (LinearLayout) this.getLayoutInflater().inflate(R.layout.table_layout, null);// 填充表名tableNameTextView = ((TextView) subLayout.findViewById(R.id.tableLayout_tableName));tableNameTextView.setText("tablename");this.addContentView(subLayout, new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT));
但是上面這段代碼執行後,table_layout布局裡面的邊距設定會正常顯示,但是activity_main布局中table_layout的邊緣卻緊緊挨著activity_main的邊緣,說明activity_main的padding並沒有其效果。
這個問題我糾結了將近3個消失,終於設定了根局部和子布局的margin和padding也不行,分別設定top、right、bottom、left也不行,最終的解決辦法卻讓我感到非常匪夷所思:
只需要在根布局中再加一個布局,把這個布局當做根布局來動態載入子布局就好了。
不知道為什麼類型完全相同的根布局就會出錯,也許‘根‘布局有某些特別的限制吧。
修改之後的代碼是:
activity_main.xml:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" tools:context=".MainActivity" > <!-- 只要這麼再加一個布局來代替跟布局就OK了。。。 --> <LinearLayout android:id="@+id/mainLayout" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" android:paddingBottom="8dp" android:paddingLeft="8dp" android:paddingRight="8dp" > </LinearLayout></LinearLayout>
源碼:
LinearLayout subLayout = (LinearLayout) this.getLayoutInflater().inflate(R.layout.table_layout, null);// 填充表名tableNameTextView = ((TextView) subLayout.findViewById(R.id.tableLayout_tableName));tableNameTextView.setText("tablename");LinearLayout mainLayout = (LinearLayout) findViewById(R.id.mainLayout); //通過這個新加的"根布局"來載入子布局mainLayout.addView(subLayout);
如果轉載請註明出處:http://blog.csdn.net/gophers?viewmode=contents