35

我正在尝试使用Toastinside OnCLickListener。我的代码触发以下错误:

The method makeText(Context, CharSequence, int) in the type Toast is not applicable for the arguments (new View.OnClickListener(){}, String, int)

这是我的代码:

    Button register = (Button) findViewById(R.id.register);
    register.setOnClickListener(new View.OnClickListener() {
        public void onClick(View arg0) {
            EditText name = (EditText)findViewById(R.id.name);
            String Lname = name.getText().toString();

            Toast.makeText(this, Lname, Toast.LENGTH_SHORT).show();



        }
    });
4

7 回答 7

94

正如肯尼所说,this指的是View.OnClickListener而不是你的Activity. 将此更改为MyActivity.this.

例如,

public class MyActivity extends Activity {
// ... other code here
Toast.makeText(MyActivity.this, Lname, Toast.LENGTH_SHORT).show();
于 2010-12-25T20:24:59.613 回答
7

在这种情况下,this指的是匿名子类的实例View.OnClickListener。您必须参考this创建匿名类的类。

于 2010-12-25T20:19:15.620 回答
4

使用MyActivity.thisasthis指您的onclickListener.

于 2013-05-14T09:01:43.123 回答
3

你也可以使用getApplicationContext()。请参阅文档

于 2013-02-16T10:15:46.443 回答
2

在任何地方,只需使用以下内容:

((Activity) mContext).runOnUiThread(new Runnable() {
                    public void run() {
                        Toast my_toast = Toast.makeText(mContext, "YOUR TEXT OR STRING", Toast.LENGTH_LONG);
                        my_toast.setGravity(Gravity.CENTER, 0, 0);
                        my_toast.show();
                    }
                });

您只需要在活动顶部定义(就在 onCreate 之后):

mContext = this;

另外,请注意我将其分解了一点,以便能够根据需要处理重力(有时您可能希望吐司出现在屏幕中央)...

于 2012-06-10T04:31:39.570 回答
1

实现目标的另一种方法是实现OnClickListener接口。这样您就可以onClick()在您的方法中实现该方法,Activity从而可以分配this. 此外,您可以分配this给多个Buttons。您可以通过方法中的相应语句Button比较它们​​的 ID,从而将这些 s 彼此区分开来。ifswitchonClick()

public class MyActivity extends Activity implements OnClickListener{

    // ...

    protected void onCreate (Bundle savedInstanceState){
        // ...
        Button register = (Button) findViewById(R.id.register);
        register.setOnClickListener(this); 
    }

    public void onClick(View arg0) {
        EditText name = (EditText) findViewById(R.id.name);
        String text = name.getText().toString();

        Toast.makeText(this, text, Toast.LENGTH_SHORT).show();
    }
}
于 2013-03-13T10:27:00.630 回答
0

试试这个

 public void onClick(View arg0) {
        EditText name = (EditText)findViewById(R.id.name);
        String Lname = name.getText().toString();
        Toast.makeText(arg0.getContext(), Lname, Toast.LENGTH_SHORT).show();
    }
于 2016-07-27T04:50:49.660 回答