I am trying to display a toast when this button is pressed. But the code is not working

↘锁芯ラ 提交于 2019-11-26 23:30:31

问题


public class MainActivity extends Activity {

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



    Button btn = (Button) findViewById(R.id.button1);
    btn.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            EditText text = (EditText)findViewById(R.id.editText1);
            EditText text1 = (EditText)findViewById(R.id.editText2);
            String userid = text.getText().toString();
            String pass = text1.getText().toString();
        Toast.makeText(getBaseContext(),"Entered"+userid+"and password entered is"+pass,Toast.LENGTH_SHORT).show();
        }

    });

}

The code executes successfully, but nothing happens when the button is pressed. When I focus on the line in eclipse it says the following

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

Please tell me what do i require to do to make it work


回答1:


You have to pass the current Context as first parameter (instead of getBaseContext()). This, in your case, is MainActivity.this.

Toast.makeText(MainActivity.this,"Entered"+userid+"and password entered is"+pass,Toast.LENGTH_SHORT).show();



回答2:


It is because the getBaseContext() at that point in the code is referencing the click listener. What you want to reference is your activity. You should change the reference of your Context in the Toast message to be View.getContext()(if working on the context from within a subview) or this.




回答3:


Toast.makeText(getApplicationContext(),"Entered"+userid+"and password entered is"+pass,Toast.LENGTH_SHORT).show();

OR

Toast.makeText(MainActivity.this,"Entered"+userid+"and password entered is"+pass,Toast.LENGTH_SHORT).show();

Method Syntax

public static Toast makeText (Context context, CharSequence text, int duration);

The context to use. Usually your Application or Activity object.



来源:https://stackoverflow.com/questions/15278118/i-am-trying-to-display-a-toast-when-this-button-is-pressed-but-the-code-is-not

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!