如何在Android中创建2个或2个以上的按钮

时间:2014-05-15 10:36:08

标签: java android sdk

我想在android中创建2个或2个以上的两个按钮,但我在这行中遇到了问题

View btnClick = findViewById(R.id.buttonClick);
    View btnscan = findViewById(R.id.btscanClick);
    //set event listener
    btnClick.setOnClickListener(this);
}

//override the OnClickListener interface method
@Override
public void onClick(View arg0) {
    if(arg0.getId() == R.id.buttonClick){
        //define a new Intent for the second Activity
        Intent intent = new Intent(this,SecondActivity.class);
        //start the second Activity
        this.startActivity(intent);

public void onClick1(View arg1) {
    if(arg1.getId() == R.id.btscanClick){
        //define a new Intent for the second Activity
        Intent intent = new Intent(this,ScanActivity.class);
        //start the second Activity
        this.startActivity(intent);

4 个答案:

答案 0 :(得分:0)

嘿,你的观点转向Button,而不是

View btnscan = findViewById(R.id.btscanClick);

使用

Button btnscan = (Button)findViewById(R.id.btscanClick);

也会发布您遇到的错误,以便我帮助您。

答案 1 :(得分:0)

将侦听器添加到其他按钮

Button btnscan = (Button)findViewById(R.id.btscanClick);
btnscan.setOnClickListener(this);

Button btnclick = (Button)findViewById(R.id.buttonClick);
btnclick.setOnClickListener(this);

让我们只用一个OnClick方法处理点击。

public void onClick(View arg0) {

if(arg0.getId() == R.id.buttonClick){
    //define a new Intent for the second Activity
    Intent intent = new Intent(this,SecondActivity.class);
    //start the second Activity
    this.startActivity(intent);
    }
else if(arg1.getId() == R.id.btscanClick){
    //define a new Intent for the second Activity
    Intent intent = new Intent(this,ScanActivity.class);
    //start the second Activity
    this.startActivity(intent);
    }
}

答案 2 :(得分:0)

可能是您的设计存在问题,我在表面视图中实现它。如果你这样做使用LinearLayout和RelativeLayout进行布局,那么如果你还添加你的.manifest文件会更好

答案 3 :(得分:0)

您通常希望为按钮定义OnClickListener的方式如下:

btnClick.setOnClickListener( new OnClickListener() {
    @Override
    public void onClick(View arg0) {
            //define a new Intent for the second Activity
            Intent intent = new Intent(this,SecondActivity.class);
            //start the second Activity
            this.startActivity(intent);
    }
});

btnScan.setOnClickListener( new OnClickListener() {
    @Override
    public void onClick(View arg0) {
            //define a new Intent for the scan Activity
            Intent intent = new Intent(this,ScanActivity.class);
            //start the second Activity
            this.startActivity(intent);
    }
});

这意味着您为每个按钮使用不同的onClickListener。