MessageDialog.java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 |
package com.phaisarn.myapplication; import android.app.Dialog; import android.content.DialogInterface; import android.os.Bundle; import android.support.v4.app.DialogFragment; import android.support.v7.app.AlertDialog; public class MessageDialog extends DialogFragment { public MessageDialog() { //Empty constructor required for DialogFragment } public static MessageDialog newInstance(String title, String msg) { MessageDialog msgDlg = new MessageDialog(); Bundle args = new Bundle(); args.putString("title", title); args.putString("message", msg); msgDlg.setArguments(args); return msgDlg; } @Override public Dialog onCreateDialog(Bundle savedInstanceState) { String title = getArguments().getString("title"); String message = getArguments().getString("message"); AlertDialog.Builder builder = new AlertDialog.Builder(getActivity()) .setTitle(title) .setMessage(message) .setPositiveButton("OK", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { // on success } }); return builder.create(); } } |
activity_main.xml
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" tools:context=".MainActivity"> <Button android:id="@+id/button1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentTop="true" android:layout_centerHorizontal="true" android:layout_marginTop="26dp" android:text="Show Alert Dialog" /> </LinearLayout> |
MainActivity.java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 |
package com.phaisarn.myapplication; import android.support.v4.app.FragmentManager; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.Button; public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); Button button1 = (Button) findViewById(R.id.button1); button1.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { showMessageDialog(); } }); } private void showMessageDialog() { FragmentManager fm = getSupportFragmentManager(); MessageDialog alertDialog = MessageDialog.newInstance("คำเตือน", "ยอดเงินของคุณใกล้จะหมด \nกรุณาเติมเงินด้วยค่ะ"); alertDialog.show(fm, null); } } |