自訂對話框的核心思路只有一句:先寫一份對話框專用的 XML 布局,再讓對話框把需要的控制項裝進去。以下以顯示文字控制項為例,換成 ImageView 等其他元件也同理。
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="https://schemas.android.com/apk/res/android"
android:layout_height="wrap_content"
android:layout_width="fill_parent"
android:background="#ffffffff"
android:orientation="vertical"
android:id="@+id/llToast" >
<TextView
android:layout_height="wrap_content"
android:layout_margin="1dip"
android:textColor="#ffffffff"
android:layout_width="fill_parent"
android:gravity="center"
android:textSize="16sp"
android:background="#FF129de2"
android:id="@+id/tvTitleToast" />
<LinearLayout
android:layout_height="wrap_content"
android:orientation="vertical"
android:id="@+id/llToastContent"
android:layout_marginLeft="1dip"
android:layout_marginRight="1dip"
android:layout_marginBottom="1dip"
android:layout_width="wrap_content"
android:padding="15dip"
android:background="#FFFFFFFF" >
<TextView
android:layout_height="wrap_content"
android:paddingRight="10dip"
android:paddingLeft="10dip"
android:layout_width="wrap_content"
android:gravity="center"
android:textSize="16sp"
android:textColor="#FFff6699"
android:id="@+id/tvTextToast" />
</LinearLayout>
<LinearLayout
android:id="@+id/MyLayout_ad2"
android:orientation="horizontal"
android:layout_width="fill_parent"
android:layout_height="40sp">
<com.tencent.exmobwin.banner.TAdView
android:id="@+id/adview2"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:gravity="top|right" >
</com.tencent.exmobwin.banner.TAdView>
</LinearLayout>
</LinearLayout>
private void ShowConnectDialog(String textString) {
LinearLayout loginLayout1 = (LinearLayout) getLayoutInflater()
.inflate(R.layout.connect_dlg, null);
TextView title = (TextView) loginLayout1.findViewById(R.id.tvTitleToast);
title.setText("系統提示");
TextView text1 = (TextView) loginLayout1.findViewById(R.id.tvTextToast);
text1.setText(textString);
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setView(loginLayout1);
builder.setPositiveButton("下載MobCtrl服務器?", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
// 處理確定按鈕
}
});
builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
// 處理取消按鈕
finish();
}
});
builder.create().show();
}
這裡的關鍵是 inflate 之後所有 findViewById 都要以 layout 根視圖為起點呼叫,而不是用 Activity 的 this.findViewById,否則抓不到對話框內的元件。
ShowConnectDialog("連接超時,請檢查服務器是否開啟及IP地址是否輸入正確。確保電腦和手機連接在同一個網絡內。");
就這三步。標題、內文、按鈕文案各自參數化之後,這個方法可以重複用來跳各種提示視窗;廣告版位那一塊若不需要,直接把對應的 LinearLayout 從布局裡移除即可。