【问题标题】:crash when I click a button单击按钮时崩溃
【发布时间】:2018-10-13 12:54:48
【问题描述】:

我有一个按钮可以进入一个新的 Activity,但是当我点击它时应用程序崩溃了。我该怎么做才能解决这个问题?这是我刚刚打开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);
            }
        });
    }
}

【问题讨论】:

  • 请添加错误日志。
  • 带有错误日志的同时也会显示您的 mainfest 文件
  • 显示你的错误日志

标签: android android-studio


【解决方案1】:

在 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);
        }
    });

使用其他 id 而不是 'home'。

希望对你有帮助

【讨论】:

    【解决方案2】:

    您已经放置在 Activity 上。所以不需要从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"/>
    

    希望这会有所帮助。

    【讨论】:

    • this 如何在 Anonymous Class 内部工作?
    • 糟糕!更新了答案。
    【解决方案3】:

    使用这个:

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

    【讨论】:

      【解决方案4】:

      更改您的代码以进行第二个活动:

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

      【讨论】:

        【解决方案5】:

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

        希望对你有所帮助。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2021-03-13
          • 2017-06-15
          • 1970-01-01
          • 2013-09-23
          • 2011-10-20
          • 2015-09-18
          • 1970-01-01
          相关资源
          最近更新 更多