Error due to invalid combination of Toast and OnClickListener

前端 未结 7 1977
醉梦人生
醉梦人生 2021-01-31 08:54

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

The method makeText(Context, CharSequence, int)          


        
7条回答
  •  遇见更好的自我
    2021-01-31 09:18

    Another approach to achieve your goal is to implement the OnClickListener interface. This way you implement the onClick() method in your Activity and you could thus assign this. In addition, you can assign this to multiple Buttons. You can distinguish these Buttons from each other by comparing their IDs via an appropriate if, respectively switch statement within the onClick() method.

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

提交回复
热议问题