java 从 Android 的 onClickListener 获取返回值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15544510/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-31 20:00:18  来源:igfitidea点击:

Getting return value from onClickListener of Android

javaandroidandroid-widget

提问by Nikhil Agrawal

Can I set variable into context like session in web development?

我可以在 Web 开发中将变量设置为像会话这样的上下文吗?

Here is my code to in which I am developing an confirmation box as soon as the Android application get started:

这是我的代码,一旦 Android 应用程序启动,我就会在其中开发一个确认框:

package com.example.alertboxandloadingwidgets;

import android.os.Bundle;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.view.Menu;
import android.widget.Toast;

public class MainActivity extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Boolean result = showConfirmationBox("Are you sure you want to do this",
        this);
    }
    public Boolean showConfirmationBox(String messageToShow, final Context context) {
        // prepare the alert box
        AlertDialog.Builder alertbox = new AlertDialog.Builder(context);
        // set the message to display
        alertbox.setMessage(messageToShow);
        // set a positive/yes button and create a listener
        alertbox.setPositiveButton("Yes",
        new DialogInterface.OnClickListener() {
            // do something when the button is clicked
            public void onClick(DialogInterface arg0, int arg1) {
                Toast.makeText(context,
                    "'Yes' button clicked", Toast.LENGTH_SHORT)
                    .show();
            }
        });
        // set a negative/no button and create a listener
        alertbox.setNegativeButton("No", new DialogInterface.OnClickListener() {
            // do something when the button is clicked
            public void onClick(DialogInterface arg0, int arg1) {
                Toast.makeText(context, "'No' button clicked",
                Toast.LENGTH_SHORT).show();
            }
        });
        // display box
        alertbox.show();
    }
}

But I want that if the yesbutton is clicked then it has to return trueand if nobutton is clicked then it has to return false.

但我希望如果yes按钮被点击,那么它必须返回true,如果no按钮被点击,那么它必须返回false

But I am not able to do so because return type of onClickListeneris void.

但我不能这样做,因为返回类型onClickListener是无效的。

Update

更新

But the problem is that I have make it generic means This method I have to write in a CommonUtilities Class From where any of the activity can use this method. So I have to set or reset the value the result parameter from where I am calling this method.

但问题是我已经使它成为通用方法,我必须在一个 CommonUtilities 类中编写此方法,其中任何活动都可以使用此方法。因此,我必须从调用此方法的位置设置或重置结果参数的值。

回答by Aleks G

Android dialogs are asynchronous, therefore you need to refactor your code to deal with this. I'm guessing you were planning to do something like this:

Android 对话框是异步的,因此您需要重构代码来处理这个问题。我猜你打算做这样的事情:

boolean result = showConfirmation(...);
if(result) {
    //do something
}
else {
    //do something else
}

You can achieve the same result with something like this:

您可以通过以下方式获得相同的结果:

public class MainActivity extends Activity {
    private boolean result;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        showConfirmationBox("Are you sure you want to do this", this);
    }

    private doOnTrueResult() {
        result = true;
        //do something
    }

    private doOnFalseResult() {
        result = false;
        //do something else
    }

    public void showConfirmationBox(String messageToShow, final Context context) {

        // prepare the alert box
        AlertDialog.Builder alertbox = new AlertDialog.Builder(context);

        // set the message to display
        alertbox.setMessage(messageToShow);

        // set a positive/yes button and create a listener
        alertbox.setPositiveButton("Yes",
        new DialogInterface.OnClickListener() {

            // do something when the button is clicked
            public void onClick(DialogInterface arg0, int arg1) {
                Toast.makeText(context,
                    "'Yes' button clicked", Toast.LENGTH_SHORT)
                    .show();
                doOnTrueResult();
            }
        });

        // set a negative/no button and create a listener
        alertbox.setNegativeButton("No", new DialogInterface.OnClickListener() {

            // do something when the button is clicked
            public void onClick(DialogInterface arg0, int arg1) {
                Toast.makeText(context, "'No' button clicked",
                Toast.LENGTH_SHORT).show();
                doOnFalseResult();
            }
        });

        // display box
        alertbox.show();
    }
}

回答by Lingasamy Sakthivel

This is how I've always handled data from dialog boxes

这就是我一直处理来自对话框的数据的方式

alertbox.setPositiveButton("Yes",
    new DialogInterface.OnClickListener() {

        // do something when the button is clicked
        public void onClick(DialogInterface arg0, int arg1) {
            Toast.makeText(context,
                "'Yes' button clicked", Toast.LENGTH_SHORT)
                .show();
               myFunction(item);
        }
    });

private void myFunction(int result){
// Now the data has been "returned" (that's not
// the right terminology)
}

Similarly, use another function for other Button

同理,对其他 Button 使用另一个函数

回答by Stefan Beike

You have to pass the value from onClickListenerto a global variableor another method. As you have correctly recognized the return type of onClickListeneris void. For a more complex solution take a look to this post

您必须将值传递onClickListener全局变量或其他方法。正如您正确识别的那样,返回类型onClickListenervoid。有关更复杂的解决方案,请查看这篇文章

回答by RobinDeCroon

Create a setterfor the result value, and change the value to the selected value in your onClick()methods.

setter为结果值创建一个,并将该值更改为您onClick()方法中的选定值。

Make showConfirmationBoxvoid ;-)

使showConfirmationBox无效;-)

回答by Robin

If the function

如果函数

public Boolean showConfirmationBox(String messageToShow, final Context context)

need to be called in the main thread, you cannot do it. You will never wait for user input on the main thread. That will cause ANR.

需要在主线程中调用,你不能这样做。您永远不会在主线程上等待用户输入。那会导致ANR。

If the function can be called in background thread, you can send a message to main thread to show the alert box, and then wait for the result. Make good use of "Handler".

如果可以在后台线程中调用该函数,则可以向主线程发送消息以显示警告框,然后等待结果。善用“处理程序”。

回答by nidhi_adiga

You can't do that but u can create a boolean variable and store true if yes and False if no and then u can use that variable accordingly

您不能这样做,但是您可以创建一个布尔变量并存储 true 如果是,则存储 False 如果不是,然后您可以相应地使用该变量

回答by Cornholio

One simple way you could do it:

一种简单的方法可以做到:

public class MainActivity extends Activity {
    public static boolean result;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        showConfirmationBox("Are you sure you want to do this", this);

    }

    public Boolean showConfirmationBox(String messageToShow, final Context context) {
        AlertDialog.Builder alertbox = new AlertDialog.Builder(context);
        alertbox.setMessage(messageToShow);
        alertbox.setPositiveButton("Yes",
            new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface arg0, int arg1) {
                Toast.makeText(context, "'Yes' button clicked", Toast.LENGTH_SHORT).show();
                MainActivity.result = true;
            }
        });

    // set a negative/no button and create a listener
    alertbox.setNegativeButton("No", new DialogInterface.OnClickListener() {

        // do something when the button is clicked
        public void onClick(DialogInterface arg0, int arg1) {
            Toast.makeText(context, "'No' button clicked",
            Toast.LENGTH_SHORT).show();
            MainActivity.result = false;
        }
    });

    // display box
    alertbox.show();

    }
}

回答by krishna

one of the option would be using the

一种选择是使用

public Button getButton (int whichButton)
Gets one of the buttons used in the dialog.

this Returns
The button from the dialog, or null if a button does not exist.

for more information check the link http://developer.android.com/reference/android/app/AlertDialog.html

有关更多信息,请查看链接http://developer.android.com/reference/android/app/AlertDialog.html

回答by Ankitkumar Makwana

this may helps you

这可能会帮助你

public class MainActivity extends Activity {
     Boolean mresult;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

          Boolean result = showConfirmationBox("Are you sure you want to do this",this);
          Toast.makeText(getApplicationContext(), ""+result, Toast.LENGTH_LONG).show();


    }

     public Boolean showConfirmationBox(String messageToShow, final Context context) {       

            AlertDialog.Builder alertbox = new AlertDialog.Builder(context);
            // set the message to display
            alertbox.setMessage(messageToShow);
            // set a positive/yes button and create a listener
            alertbox.setPositiveButton("Yes",
            new DialogInterface.OnClickListener() {
                // do something when the button is clicked
                public void onClick(DialogInterface arg0, int arg1) {
                    Toast.makeText(context,
                        "'Yes' button clicked", Toast.LENGTH_SHORT)
                        .show();

                    mresult = true;
                }
            });
            // set a negative/no button and create a listener
            alertbox.setNegativeButton("No", new DialogInterface.OnClickListener() {
                // do something when the button is clicked
                public void onClick(DialogInterface arg0, int arg1) {
                    Toast.makeText(context, "'No' button clicked",
                    Toast.LENGTH_SHORT).show();

                    mresult = false;
                }
            });
            // display box
            alertbox.show();
            return mresult;
        }


}