从另一个类调用对话框

时间:2013-04-03 10:16:31

标签: android dialog alertdialog

我得到了以下内容:

  • 一个名为DConce的类,其中包含我将要使用的一个对话框的代码:

        public class DConce extends DialogFragment{
    
    public Dialog onCreateDialog(Bundle savedInstanceState) {
    AlertDialog.Builder dshow = new AlertDialog.Builder(getActivity());
    
    LayoutInflater inflater = getActivity().getLayoutInflater();
    
    dshow.setView(inflater.inflate(R.layout.dialogconc, null))
    
           .setPositiveButton("Send", new DialogInterface.OnClickListener() {
               @Override
               public void onClick(DialogInterface dialog, int id) {
    
                   //TODO
    
    
               }
           })
           .setNegativeButton("Close", new DialogInterface.OnClickListener() {
               public void onClick(DialogInterface dialog, int id) {
                   DConce.this.getDialog().cancel();
               }
           });      
    
    return dshow.create();
    
    }
    

将另一个类放入一个名为public final class Sincr extends Fragment的片段中,我需要调用对话框:

 case R.id.btnConce:
    //here      
            break;

我该怎么做?

提前感谢。

4 个答案:

答案 0 :(得分:2)

修改DialogFragment:

public class DConce extends DialogFragment{

  public static DConce newInstance(){
    DConce f = new DConce();
    return f;
  }

  public Dialog onCreateDialog(Bundle savedInstanceState) {
    AlertDialog.Builder dshow = new AlertDialog.Builder(getActivity());

    LayoutInflater inflater = getActivity().getLayoutInflater();

    dshow.setView(inflater.inflate(R.layout.dialogconc, null))
      .setPositiveButton("Send", new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int id) {
           //TODO
        }
      })
      .setNegativeButton("Close", new DialogInterface.OnClickListener() {
        public void onClick(DialogInterface dialog, int id) {
          DConce.this.getDialog().cancel();
        }
      });     
    return dshow.create();
  }    
}

然后展示它;

case R.id.btnConce:
  DConce.newInstance().show(getChildFragmentManager(), null);
  break;

您当然可以选择为String参数传递tag,以唯一标识该片段。

答案 1 :(得分:2)

您需要添加到代码中的是newInstance,例如:

public static DConce newInstance(){
    DConce arg = new DConce();
    return arg;
  }

然后在活动中:

FragmentManager manager = getSupportFragmentManager(); // or getFragmentManager, depends on which api lvl you are working on but supportFragmentManager will make you dialog work also on devices lower than api lvl 11(3.0 - > Honeycomb)
DialogFragment Dialog = DConce.newInstance();
Dialog.show(manager, "tag");

答案 2 :(得分:-1)

答案 3 :(得分:-1)

创建静态方法并将代码放入其中。

并直接按类名称致电,Dcon.myAlertMessage()