(二)AS给button添加点击事件

三种方法给Button添加点击事件

(一)通过button的id,添加继承View.OnClickListener的监听实现

    <Button
        android:id="@+id/btn_button2"
        android:text="按钮2"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />
public class MainActivity extends AppCompatActivity implements View.OnClickListener {

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

        findViewById(R.id.btn_button2).setOnClickListener(this);
        
    }


    @Override
    public void onClick(View v) {
        if(v.getId()==R.id.btn_button2)
        {
            Toast.makeText(getApplicationContext(),"Button 2 clicked",Toast.LENGTH_LONG).show();
        }
    }
}

(二)通过Text直接绑定点击事件

    <Button
        android:onClick="button1OnClick"
        android:layout_width="match_parent"
        android:text="按钮1"
        android:layout_height="wrap_content" />
public class MainActivity extends AppCompatActivity implements View.OnClickListener {

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


    }

    public void button1OnClick(View view) {
        Toast.makeText(getApplicationContext(),"Button 1 clicked",Toast.LENGTH_LONG).show();
    }

}

(二)在setOnClickListener中直接添加方法

    <Button
        android:id="@+id/btn_button3"
        android:text="按钮3"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />
public class MainActivity extends AppCompatActivity implements View.OnClickListener {

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

        findViewById(R.id.btn_button3).setOnClickListener(new View.OnClickListener(){
            @Override
            public void onClick(View v) {
                Toast.makeText(getApplicationContext(),"Button 3 clicked",Toast.LENGTH_LONG).show();
            }
        });

    }

}

 

posted @ 2018-11-06 09:57  81192  阅读(5838)  评论(0编辑  收藏  举报