如何在onclick函数中调用我的对话框函数?

时间:2014-05-15 10:30:39

标签: android onclick android-dialog

我不知道如何将对话框功能添加到我的onclick功能中,我希望一旦我点击按钮就可以召唤对话框。

这是oncreate方法

 /** Called when the activity is first created. */
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.listview);
    fillData();
    boxAdapter = new ListAdapter(this, products);

    ListView lvMain = (ListView) findViewById(R.id.lvMain);
    lvMain.setAdapter(boxAdapter);


    Button btn = (Button) findViewById(R.id.insert);

    OnClickListener listener = new OnClickListener() {          
        @Override
        public void onClick(View v) {                               


        }
    };

    /** Setting the event listener for the add button */
    btn.setOnClickListener(listener);       



  }

然后这是我的对话框函数,它位于同一个java类

public Dialog onCreateDialog(Bundle savedInstanceState) {
      AlertDialog.Builder builder = new AlertDialog.Builder(this);
      // Get the layout inflater
      LayoutInflater inflater = this.getLayoutInflater();

      // Inflate and set the layout for the dialog
      // Pass null as the parent view because its going in the dialog layout
      builder.setView(inflater.inflate(R.layout.dialog, null))
      // Add action buttons
             .setPositiveButton(R.string.Insert, new DialogInterface.OnClickListener() {
                 @Override
                 public void onClick(DialogInterface dialog, int id) {

                 }
             })
             .setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
                 public void onClick(DialogInterface dialog, int id) {
                    // DialogFragment.this.getDialog().cancel();
                 }
             });      
      return builder.create();
  }

2 个答案:

答案 0 :(得分:0)

这里的答案是,将Bundle作为最终的

public void onCreate(final Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.listview);
    fillData();
    boxAdapter = new ListAdapter(this, products);

ListView lvMain = (ListView) findViewById(R.id.lvMain);
lvMain.setAdapter(boxAdapter);


Button btn = (Button) findViewById(R.id.insert);

OnClickListener listener = new OnClickListener() {          
    @Override
    public void onClick(View v) {                               
            Dialog d = onCreateDialog(savedInstanceState);
            d.show();

    }
};

/** Setting the event listener for the add button */
btn.setOnClickListener(listener);       

}

答案 1 :(得分:0)

对话框功能中,您不必传递参数Bundle savedInstanceState,然后在您的onClick函数中为您的按钮调用如下函数:

  OnClickListener listener = new OnClickListener() {          
        @Override
        public void onClick(View v) {                               
Dialog dialog = onCreateDialog(); // assuming that you will remove the argmunent
dialog.show();

        }
    };