由于Toast和OnClickListener的无效组合而导致的错误 [英] Error due to invalid combination of Toast and OnClickListener

查看:107
本文介绍了由于Toast和OnClickListener的无效组合而导致的错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在 OnCLickListener 中使用 Toast .我的代码触发了以下错误:

I'm trying to use Toast inside OnCLickListener. My code triggers the following error:

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();



        }
    });

推荐答案

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

As The Kenny said, this is refering to the View.OnClickListener instead of your Activity. Change this, to MyActivity.this.

例如,

public class MyActivity extends Activity {
// ... other code here
Toast.makeText(MyActivity.this, Lname, Toast.LENGTH_SHORT).show();

这篇关于由于Toast和OnClickListener的无效组合而导致的错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆