1. 程式人生 > >我的安卓進階之路(二)

我的安卓進階之路(二)

    這周結束了“活動”,開始了UI的征程。

    1、七大控制元件

          踩的兩個小坑

         第一個,ImageView即圖片控制元件,名稱必須以字母開頭。如1img不行,而img2可以,倒是和變數名的命名相類似。

         第二個,就是對對話方塊控制元件的使用

AlertDialog.Builder dialog=new AlertDialog.Builder(MainActivity.this);
dialog.setTitle("This is a dialog");
dialog.setMessage("something important");
dialog.setCancelable(false);
dialog.setPositiveButton("OK",new DialogInterface.OnClickListener(){
@Override
public void onClick(DialogInterface dialog, int which) {
}
});
dialog.setNegativeButton("Cancel",new DialogInterface.OnClickListener(){
@Override
public void onClick(DialogInterface dialog, int which) {
}
});
dialog.show();

 首先通過AlertDialog.Builder建立一個AlertDialog的例項,然後給這個對話方塊設定標題,內容,可否取消等屬性。呼叫setPositiveButton()方法設定點選確定觸發的事件,setNegativeButton()方法設定點選取消觸發的事件。

2、四大布局

     線性佈局、相對佈局、幀佈局和百分比佈局。

     前三個較為簡單,百分比佈局,則較為特殊。 定義在support庫中,使用前在專案的buile.gradle中新增百分比佈局庫的依賴。

dependencies {
compile fileTree(dir: 'libs', include: ['*.jar'])
androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
exclude group: 'com.android.support', module: 'support-annotations'
})
compile 'com.android.support:appcompat-v7:24.2.1'
compile 'com.android.support:percent:24.2.1'//加上這一行程式碼
testCompile 'junit:junit:4.12'
}

即在dependencies閉包中作此修改。  

然後直接修改控制元件寬高百分比屬性。

     由於百分比佈局並不是內建在SDK當中,所以需要把完整的包路經寫出來,在定義一個app的名稱空間。

<Button
        android:id="@+id/button2"
        android:text="button 2"
        android:layout_gravity="right|top"
        app:layout_widthPercent="50%"
        app:layout_heightPercent="50%"/>

類似如此的操作。