单击按钮时崩溃

时间:2018-05-03 09:10:30

标签: android android-studio

我有一个按钮可以访问新的Activity,但是当我点击它时应用程序崩溃了。我该怎么做才能解决这个问题?这是我刚刚打开活动的代码

public class Programvare extends AppCompatActivity {

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

        Button home = (Button)findViewById(R.id.home);
        home.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                Intent startIntent = new Intent (getApplicationContext(), MainActivity.class);
                // Show how to pass Information to another Activity
                startActivity(startIntent);
            }
        });
    }
}

5 个答案:

答案 0 :(得分:1)

您已经放置了一项活动。因此,无需从getApplicationContext()获取上下文。使用此代替getApplicationContext()

Intent startIntent = new Intent (Programvare.this, MainActivity.class);
// Show how to pass Information to another Activity
startActivity(startIntent);

并检查AndroidManifest.xml。是否添加了MainActivity。如果没有,请在活动列表中添加MainActivity,如下所示。

<activity android:name=".MainActivity"/>

希望这会有所帮助。

答案 1 :(得分:0)

更改您的代码以进入第二项活动:

Intent startIntent = new Intent (Programvare.this, MainActivity.class);
// Show how to pass Information to another Activity
startActivity(startIntent);

答案 2 :(得分:0)

在Xml中定义

<Button
            android:layout_width="match_parent"
            android:id="@+id/my_button"
            android:layout_height="wrap_content" />

活动

 Button myButton = (Button)findViewById(R.id.my_button);
    myButton.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            Intent startIntent = new Intent (Programvare.this, MainActivity.class);
            // Show how to pass Information to another Activity
            startActivity(startIntent);
        }
    });

而不是&#39; home&#39;使用其他ID。

希望它可以帮到你

答案 3 :(得分:0)

使用它:

  Intent startIntent = new Intent (Programvare.this, MainActivity.class);
  startActivity(startIntent);

答案 4 :(得分:0)

检查AndroidManifest.xml它应该包括所有项目活动。

希望它可能会有所帮助。

相关问题