在編寫代碼過程中,對於彈出框,事先寫好的佈局文件往往不能滿足我們的需求,這時我們需要自己定義樣式。
1、首先新建一個xml文件,這裏以設置音效開關爲例
myview.xml如下:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<TextView
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBottom="@+id/toggleButton1"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:text="@string/voice"
android:textSize="20sp" />
<ToggleButton
android:id="@+id/toggleButton1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_toRightOf="@+id/textView1"
android:text="ToggleButton"
android:textOff="OFF"
android:textOn="ON" />
</RelativeLayout>
2、在代碼中調用自定義視圖
public void setSound(){
// 取得自定義View
LayoutInflater layoutInflater = LayoutInflater.from(MainActivity.instance); //MainActivity.instance是在MainActivity.java中定義的,public static MainActivity instance;
View myLoginView = layoutInflater.inflate(R.layout.myview, null);
myToggleButton = (ToggleButton)myLoginView.findViewById(R.id.toggleButton1);
if(audio_on){
myToggleButton.setChecked(true);
}else{
myToggleButton.setChecked(false);
}
Dialog alertDialog = new AlertDialog.Builder(MainActivity.instance)
.setTitle("設置")
.setView(myLoginView)
.setIcon(android.R.drawable.ic_dialog_info)
.setPositiveButton("確定",new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
if(myToggleButton.isChecked()){
audio_on = true;
}else{
audio_on = false;
}
}
}).
create();
alertDialog.show();
}
這是遊戲的菜單界面:
點擊設置後彈出設置音效開關對話框,調用setSound()方法:
3、相關知識點補充
在實際開發中LayoutInflater這個類還是非常有用的,它的作用類似於findViewById()。不同點是LayoutInflater是用來找res/layout/下的xml佈局文件,並且實例化;而findViewById()是找xml佈局文件下的具體widget控件(如Button、TextView等)。
具體作用:
1、對於一個沒有被載入或者想要動態載入的界面,都需要使用LayoutInflater.inflate()來載入;
2、對於一個已經載入的界面,就可以使用Activiyt.findViewById()方法來獲得其中的界面元素。