Android developers have provided us based on how to create a custom dialog by using alertdialog.builder method. If you are interesting with it, here’s the link. http://developer.android.com/guide/topics/ui/dialogs.html
I am going to shows another way instead of using alertdialog.builder. What is the benefit of this method is you can update the content of dialog view dynamically and directly.
If you are thinking changing the content of dialog when the button is pressed without closing dialog. You might give a try on this method.
First, create the layout for custom dialog
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<TextView
android:id="@+id/dialog_text"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="this is custom dialog"/>
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<Button
android:id="@+id/dialog_positive_button"
android:layout_width="0dip"
android:layout_height="wrap_content"
android:layout_weight="0.5"
android:text="positive"/>
<Button
android:id="@+id/dialog_negative_button"
android:layout_width="0dip"
android:layout_height="wrap_content"
android:layout_weight="0.5"
android:text="negative"/>
</LinearLayout>
</LinearLayout>
Then, create the custom dialog class
class SimpleCustomDialog extends AlertDialog{ TextView text; SimpleCustomDialog(Context ctx){ super(ctx); setTitle("Custom Dialog"); LayoutInflater inflater = getLayoutInflater(); View view = inflater.inflate(R.layout.alertdialog_layout, null); text = (TextView)view.findViewById(R.id.dialog_text); text.setText("this is custom dialog"); Button positiveButton = (Button)view.findViewById(R.id.dialog_positive_button); Button negativeButton = (Button)view.findViewById(R.id.dialog_negative_button); positiveButton.setOnClickListener(new PositiveButtonListener()); negativeButton.setOnClickListener(new NegativeButtonListener()); setView(view); } class PositiveButtonListener implements View.OnClickListener{ @Override public void onClick(View view) { text.setText("Button clicked"); } } class NegativeButtonListener implements View.OnClickListener{ @Override public void onClick(View view) { // dialog wouldn't dismiss itself, you have to call dismiss method //dismiss dialog SimpleCustomDialog.this.dismiss(); } } }
finally call show method to show dialog
SimpleCustomDialog mDialog = new SimpleCustomDialog(this);
mDialog.show();
If you want to dismiss the dialog, just call dismiss method.
Hope this article helps you. Thank your for reading.
0 件のコメント:
コメントを投稿