好處是不用寫layout, 比較簡單
壞處是Dialog內容只適合放條列文字, 如果要編排圖文位置就不方便了
Context context = 類別名稱.this;
final AlertDialog.Builder mAB = new AlertDialog.Builder(context);
final AlertDialog.Builder mAB = new AlertDialog.Builder(context);
final DialogInterface.OnClickListener di_onclick = new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface dialog, int which)
{
switch(which)
{
case ID_SELECT: //int ID_SELECT = 0;
break;
case ID_DELETE: //int ID_DELETE = 1;
break;
}
}
};
mAB.setTitle(R.string.str_dialog_title);
mAB.setIcon(R.drawable.dialog_title_icon);
mAB.setItems(R.array.dialog_item, di_onclick);
亦可使用setItems(CharSequence[] items, DialogInterface.OnClickListener listener)如下
String yy[] = new String[]{"1","2" ,"3"};
mAB.setItems(yy, di_onclick);
AlertDialog alert = mAB.create();
alert.show();
./res/values/arrays.xml
<resources>
<string-array name="dialog_item">
<item>Launch</item>
<item>Uninstall</item>
</string-array>
</resources>
<string-array name="dialog_item">
<item>Launch</item>
<item>Uninstall</item>
</string-array>
</resources>
若要關閉此對話框則下
alert.dismiss();
=============================加入view的AlertDialog=================================
好處是想在Dialog內加Image, EditText, ListView, GridView, ... 都可以
壞處是要補足的資料比較多
final AlertDialog.Builder mAB = new AlertDialog.Builder(context);
LayoutInflater factory = LayoutInflater.from(context);
final View view = factory.inflate(R.layout.layout_view, null);
mAB.setView(view);
TextView dialog_item1 = (TextView) view.findViewById(R.id.dialog_item1);
TextView dialog_item2 = (TextView) view.findViewById(R.id.dialog_item2);
dialog_item1.setOnClickListener(new OnClickListener()
{
@Override
public void onClick(View v)
{
}
});
dialog_item2.setOnClickListener(new OnClickListener()
{
@Override
public void onClick(View v)
{
}
});
AlertDialog alert = mAB.create();
alert.show();
./res/layout/layout_view
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical"
>
<TextView
android:layout_width="match_parent"
android:layout_height="80dp"
android:text="@string/str_dialog_title"
android:gravity="center_horizontal"
/>
<TextView
android:id="@+id/dialog_item1"
android:layout_width="match_parent"
android:layout_height="80dp"
android:text="@string/str_dialog_item1"
android:gravity="clip_vertical"
/>
<TextView
android:id="@+id/dialog_item2"
android:layout_width="match_parent"
android:layout_height="80dp"
android:text="@string/str_dialog_item2"
android:gravity="clip_vertical"
/>
</LinearLayout>
若要關閉此對話框則下
alert.dismiss();
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
但以上兩種方法都難以調整Dialog的寬度(筆者是苦惱很久都試不出來)
所以便衍生了第3種方式
沒有留言:
張貼留言