Android 布局學習之——Layout(布局)詳解一
有兩種方式聲明layout: 1.在xml檔案中聲明UI組件。 2.在運行時,執行個體化布局元素。我們可以以編碼的方式建立View或ViewGroup對象,操縱它們的屬性。 下面用一個小例子來學習怎樣以編碼的方式添加layout: 複製代碼 1 import android.app.Activity; 2 import android.graphics.Color; 3 import android.os.Bundle; 4 import android.view.ViewGroup; 5 import android.widget.Button; 6 import android.widget.LinearLayout; 7 import android.widget.TextView; 8 9 public class MainActivity extends Activity {10 11 private LinearLayout linearLayout;12 private TextView textView;13 private Button button;14 public static final int VERTICAL = 1;15 public static final int MATCH_PARENT = -1;16 public static final int WRAP_CONTENT = -2;17 @Override18 protected void onCreate(Bundle savedInstanceState) {19 super.onCreate(savedInstanceState);20 21 //以編碼的方式添加layout22 23 linearLayout = new LinearLayout(this);24 linearLayout.setOrientation(VERTICAL); //設定LinearLayout方向,0是水平,1是垂直。預設是水平。25 //設定布局參數,-1是MATCH_PARENT,-2是WRAP_CONTENT26 //ViewGroup.LayoutParams(int width, int height)27 linearLayout.setLayoutParams(new ViewGroup.LayoutParams(MATCH_PARENT,MATCH_PARENT));28 29 textView = new TextView(this);30 textView.setText("ThisIsATextView");31 textView.setBackgroundColor(Color.RED);32 textView.setLayoutParams(new ViewGroup.LayoutParams(MATCH_PARENT,WRAP_CONTENT));33 34 button = new Button(this);35 button.setText("ThisIsAButton");36 button.setBackgroundColor(Color.GREEN);37 button.setLayoutParams(new ViewGroup.LayoutParams(MATCH_PARENT,WRAP_CONTENT));38 39 linearLayout.addView(button);40 linearLayout.addView(textView);41 //布局寫好後,不要忘記添加到Activity中42 setContentView(linearLayout);43 44 45 }46 }複製代碼 運行: 每個layout檔案必須包含一個確定的根項目,這個根項目它必須是View或ViewGroup的對象。 那View類和ViewGroup類的作用是什麼呢? View: 為使用者介面組件提供基本的搭建地區 。View類是widgets的父類,widgets通常用來建立互動UI組件 如button,TextView等等。View類同時也是ViewGroup類的父類。 ViewGroup: 是layout類的父類,而layout類是儲存其他View或ViewGroup的可視化容器(invisible containers),並且能定義它們的布局屬性。 通過添加額外的布局對象(layout object)或視窗(widgets)作為子項目來逐漸完善視圖層。 下面通過一個layout檔案來具體學習以下: 複製代碼 1 <!-- 確定的根項目 LinearLayout是ViewGroup的子類layout的對象 --> 2 <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 3 xmlns:tools="http://schemas.android.com/tools" 4 android:layout_width="match_parent" 5 android:layout_height="wrap_content" 6 android:orientation="vertical" > 7 <!-- 添加子組件來豐富視圖層 --> 8 <Button 9 android:layout_width="match_parent"10 android:layout_height="wrap_content"11 android:background="#f00"12 android:layout_weight="1"13 android:text="ThisIsAButton" />14 <TextView 15 android:layout_width="match_parent"16 android:layout_height="wrap_content"17 android:background="#0f0"18 android:text="ThisIsATextView"19 />20 </LinearLayout>