歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux編程 >> Linux編程 >> Android中的AlertDialog使用示例二(普通選項對話框)

Android中的AlertDialog使用示例二(普通選項對話框)

日期:2017/3/1 9:07:39   编辑:Linux編程

在Android開發中,我們經常會需要在Android界面上彈出一些對話框,比如詢問用戶或者讓用戶選擇。這些功能我們叫它Android Dialog對話框,AlertDialog實現方法為建造者模式。下面我們簡單模擬一個選花魁的簡單普通選項(單選)對話框,如下圖:

Layout界面代碼:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">
<Button
android:text="普通選項"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:onClick="show2"
android:id="@+id/button2" />
</LinearLayout>

Java功能實現代碼:

public class AlertDialogDemo extends AppCompatActivity {
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.alertdialog);
}
public void show2(View v){
//實例化建造者
AlertDialog.Builder builder = new AlertDialog.Builder(this);
//設置警告對話框標題
builder.setTitle("選花魁喽");
//定義警告框選擇窗體的內容(這裡用String數組)
final String[] beautifulGirls = {"芙蓉姐姐","鳳姐","范爺","我自己"};
//將數組內的元素設置到dialog的每個item中,並做事件處理(這裡用土司)
builder.setItems(beautifulGirls, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
Toast.makeText(AlertDialogDemo.this,beautifulGirls[which]+"被選中啦",Toast.LENGTH_SHORT).show();
}
});
//顯示對話框
builder.show();
}
}

Copyright © Linux教程網 All Rights Reserved