Toast和OnClickListener无效组合导致错误
我想在OnCLickListener使用Toast 。 我的代码触发以下错误:
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而不是你的Activity 。 改变这个, MyActivity.this 。
例如,
public class MyActivity extends Activity { // ... other code here Toast.makeText(MyActivity.this, Lname, Toast.LENGTH_SHORT).show();
在这种情况下, this指的是View.OnClickListener的匿名子类的View.OnClickListener 。 你必须参考你创build匿名类的类。
使用MyActivity.this因为this是指您的onclickListener 。
你也可以使用getApplicationContext() 。 请参阅文档 。
任何地方,只要使用以下内容:
((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;
此外,请参阅我分解了一下,以便能够处理重力,因为我想(有时你可能希望吐司出现在屏幕的中心)…
实现您的目标的另一种方法是实现OnClickListener接口。 这样你在你的Activity实现了onClick()方法,你可以这样分配this 。 另外,您可以将其分配给多个Button 。 您可以通过在onClick()方法中分别通过适当的if语句和switch语句比较它们的ID来区分这些Button 。
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(); } }
尝试这个
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(); }