【问题标题】:how to set an onclick listener for an imagebutton in an alertdialog如何在警报对话框中为图像按钮设置 onclick 侦听器
【发布时间】:2011-04-28 01:54:43
【问题描述】:

我有一个带有在 AlertDialog 中膨胀的 ImageButton 的布局,我应该在哪里/如何设置 onClick 侦听器?

这是我尝试使用的代码:

    ImageButton ib = (ImageButton) findViewById(R.id.searchbutton);
    ib.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Toast.makeText(TravelBite.this, "test", Toast.LENGTH_SHORT).show();
        }
    });

【问题讨论】:

  • 我发现我做错了,我需要先从充气视图中找到 ImageButton。

标签: android onclick android-alertdialog imagebutton


【解决方案1】:

试着在你的代码中这样写

例如:-如果您的警报对话框的对象是广告,那么

 ImageButton ib = (ImageButton) ad.findViewById(R.id.searchbutton);
    ib.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Toast.makeText(TravelBite.this, "test", Toast.LENGTH_SHORT).show();
        }
    });

【讨论】:

    【解决方案2】:

    上面的代码被证明是有用的,但我在上下文中使用了“this”(而不是“ad”):

        ImageButton ib = (ImageButton) this.findViewById(R.id.searchbutton);
        ib.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Toast.makeText(TravelBite.this, "test", Toast.LENGTH_SHORT).show();
            }
    

    这更容易复制和粘贴 ;-)

    感谢之前的代码,如果没有它,我会找到上面的解决方案。

    【讨论】:

      【解决方案3】:

      在您的代码中尝试这样做。

      public void showAlertDialogButtonClicked(View view) {
      
          // create an alert builder
          AlertDialog.Builder builder = new AlertDialog.Builder(this);
          builder.setTitle("Name");
      
          // set the custom layout
          final View customLayout = getLayoutInflater().inflate(R.layout.custom_layout, null);
          builder.setView(customLayout);
      
          // add a button
          builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
              @Override
              public void onClick(DialogInterface dialog, int which) {
                  // send data from the AlertDialog to the Activity
                  EditText editText = customLayout.findViewById(R.id.editText);
                  sendDialogDataToActivity(editText.getText().toString());
              }
          });
      
          // create and show the alert dialog
          AlertDialog dialog = builder.create();
          dialog.show();
      }
      

      使用此方法

        <Button android:layout_width="match_parent"
      android:layout_height="wrap_content" android:onClick="showAlertDialogButtonClicked"/>
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2023-04-07
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多