How to implement OnClickListener on Android

前端 未结 5 675
眼角桃花
眼角桃花 2021-01-06 16:26

I learn from

http://developer.android.com/reference/android/widget/Button.html

that \"instead of applying an OnClickListener to the button

5条回答
  •  误落风尘
    2021-01-06 17:06

    You don't need implement OnClickListener, because your button execute the method automatically.

    Edit:

    public class MainActivity extends Activity {
    
    private OnClickListener onClickListener;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        if (savedInstanceState == null) {
            getFragmentManager().beginTransaction()
                    .add(R.id.container, new PlaceholderFragment()).commit();
        }
        initListener();//Initializing Listener.
        Button button = (Button)findViewById(R.id.try_button);
        //This command causes problem
        button.setOnClickListener(onClickListener);
    }
    
    private void initListener(){
             onclickListener = new OnClickListener() {
                   @Override
                    public void onClick(View view) {
                          Toast.makeText(getApplicationContext(),
                          "Button Clicked",Toast.LENGTH_SHORT).show();
                    }
             };
    }
    

    Quit the Onclick in your XML.

提交回复
热议问题