2016-09-25 5 views
4

Я нахожусь новичок в Android, вместо того, чтобы писать код повторно для диалога в каждой деятельности, я просто создал один класс, который содержит все методы, чтобы показать диалоговое окно, я дал небольшой фрагмент кодаВызов диалог из другого класса

public class Dialogues extends Activity implements DialogueMethods { 


    public void showAlertDialog(Context context, String title, String message) { 

     AlertDialog.Builder alertDialog = new AlertDialog.Builder(context); 
     alertDialog.setTitle(title); 
     alertDialog.setMessage(message); 
     alertDialog.show(); 
} 

    //this method am calling 

    public void showAlertDialog(Context context, String title, String message, String ButtonText, boolean cancel) { 

     AlertDialog.Builder alertDialog = new AlertDialog.Builder(context); 
     alertDialog.setTitle(title); 
     alertDialog.setMessage(message); 

     if(cancel) { 

      alertDialog.setNegativeButton(ButtonText, new DialogInterface.OnClickListener() { 
      @Override 
      public void onClick(DialogInterface dialog, int which) { 
       dialog.cancel(); 
       finish(); 
      } 
     }); 
     } 

     alertDialog.show(); 
    } 

} 

звонит

//dialogObj is instance of the above class 

dialogObj.showAlertDialog(MyActivity.this, "Error", "Not Connected to Internet", "Exit", true); 

Когда я запускаю диалог кода виден, но кнопка не, это из-за DialogInterace.onClickListener ?, Я просто хочу знать, это хорошая идея, чтобы сделать как это ?, если это то, что это правильный способ сделать. пожалуйста помогите.

спасибо.

ответ

4

Просто я хочу поделиться мой путь к вам, как Я использую. Вы можете создать класс, а затем позвонить туда, где хотите.

public class DialogsUtil { 

private Context mContext; 

public DialogsUtil(Context context) { 
    this.mContext = context; 
} 

/** 
* Return an alert dialog 
* 
* @param message message for the alert dialog 
* @param listener listener to trigger selection methods 
*/ 
public void openAlertDialog(Context context, String message, String positiveBtnText, String negativeBtnText, 
          final OnDialogButtonClickListener listener) { 

    AlertDialog.Builder builder = new AlertDialog.Builder(context); 
    builder.setPositiveButton(positiveBtnText, (dialog, which) -> { 
     dialog.dismiss(); 
     listener.onPositiveButtonClicked(); 

    }); 

    builder.setNegativeButton(negativeBtnText, (dialog, which) -> { 
     dialog.dismiss(); 
     listener.onNegativeButtonClicked(); 

    }); 
    builder.setTitle(context.getResources().getString(R.string.app_name)); 
    builder.setMessage(message); 
    builder.setIcon(android.R.drawable.ic_dialog_alert); 
    builder.setCancelable(false); 
    builder.create().show(); 
} 

/** 
* return a dialog object 
* @return 
*/ 
public Dialog openDialog(@LayoutRes int layoutId) { 
    Dialog dialog = new Dialog(mContext); 
    dialog.requestWindowFeature(Window.FEATURE_NO_TITLE); 
    dialog.getWindow().setBackgroundDrawableResource(android.R.color.transparent); 
    dialog.setContentView(layoutId); 
    dialog.getWindow().setLayout(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT); 
    dialog.getWindow().setGravity(Gravity.BOTTOM); 
    dialog.setCancelable(true); 
    dialog.setCanceledOnTouchOutside(false); 
    return dialog; 
} 
} 

и я создал один интерфейс для этого диалога,

public interface OnDialogButtonClickListener { 

void onPositiveButtonClicked(); 

void onNegativeButtonClicked(); 
} 

Просто реализовать этот интерфейс в вашей деятельности, где вы хотите использовать диалог и с помощью объекта класса вы можете использовать диалоговое окно, как это,

mDialogsUtil.openAlertDialog(YourActivity.this, "text message", "positive button msg", "Negative button msg", this); 

вы можете переопределить эти два метода в вашем acitivty,

@Override 
public void onPositiveButtonClicked() { 

} 

//user clicked cancel.Close the application 
@Override 
public void onNegativeButtonClicked() { 

} 

Спасибо, что это поможет вам.

+0

Спасибо за расчистку. – Manjunath

+0

Отлично, рад помочь вам :) – Saveen

0

Лучший способ определить все диалоги в базовом классе, а затем вызвать его

Class BaseActivity extends Activity{ 

int DIALOG_X = 1; 
int DIALOG_Y = 2; 
int DIALOG_Z = 3; 
// More Dialog identifiers 

ProgressDialog progressDialog; 
AlertDialog alertDialog; 
//More dialog objects if you need 

protected Dialog onCreateDialog(int id) { 
    Dialog dialog; 
    switch(id) { 
    case DIALOG_X: 
     // do the work to define the X Dialog 
     break; 
    case DIALOG_Y: 
     // do the work to define the Y Dialog 
     break; 
    default: 
     dialog = null; 
    } 
    return dialog; 
} 
} 

Тогда еще один класс продлить BaseActivity и вызвать

showDialog(DIALOG_X); 
Смежные вопросы