2个不同的按钮和

时间:2014-04-15 13:06:10

标签: java android

我玩一些Android开发,我试图创建2个具有2个不同功能的按钮。

当你启动应用程序时,你可以通过一些按钮获得此屏幕,然后选择哪一个。

到目前为止,这就是我的代码:

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


        Button startGame = (Button)findViewById(R.id.ivenever);
        Button howTo = (Button)findViewById(R.id.howto);

        startGame.setOnClickListener(this);
        howTo.setOnClickListener(this);

    }
    @Override
    public void onClick(View v) {
        // TODO Auto-generated method stub
        switch(v.getId()) { //Get the id of the button that was clicked
        case R.id.ivenever:
            Intent i = new Intent(MainActivity.this, StartGame.class);
            startActivity(i);
            break;
        case R.id.howto:
            Intent e = new Intent(MainActivity.this, HowTo.class);
            startActivity(e);
            break;
        }
    }

在我尝试创建按钮时。两个按钮都获得了每个xml代码和id。 StartGame.class工作正常,但是howto按钮只会让应用程序崩溃。

logcat的:

04-15 15:21:43.403: E/AndroidRuntime(24075): 
java.lang.RuntimeException: 
Unable to start activity 
ComponentInfo{com.name.name/com.name.name.HowTo}:   
android.content.res.Resources$NotFoundException: 
Resource ID #0x7f05003e type #0x12 is not valid

HowTo.java文件: 套餐包括在内

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;

public class HowTo extends Activity{

    protected void onCreate(Bundle savedInstanceState){
        super.onCreate(savedInstanceState);
        setContentView(R.id.howto);

        Button ivenever = (Button)findViewById(R.id.game);
        ivenever.setOnClickListener(new OnClickListener(){
            @Override
              public void onClick(View v) {
                Intent i = new Intent(HowTo.this, StartGame.class);
              }
        });
    }
}

1 个答案:

答案 0 :(得分:2)

您需要将布局的内容设置为活动。你有setContentView(R.id.howto);的错误。

所以改为

setContentView(R.layout.HowTo);