【问题标题】:Yet another try - button click is making my widgets vanish又一次尝试 - 按钮单击使我的小部件消失
【发布时间】:2023-04-11 06:20:01
【问题描述】:

当我注释掉设置按钮的 OnClickHandler 的行时,Activity 中的小部件显示正常;但是,当该行 not 被注释掉时,显示的只是顶部条带中的项目名称。 ???

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

public class OnDemandAndAutomatic_Activity extends Activity implements View.OnClickListener {

    Button buttonAuthorizeUsers;

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.ondemandandautomatic_activity);

        buttonAuthorizeUsers = (Button) findViewById(R.id.buttonAuthorizeUsers);
        //buttonAuthorizeUsers.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        // TODO Auto-generated method stub
        Intent configure = new  Intent(OnDemandAndAutomatic_Activity.this, Configure_Activity.class);  
        OnDemandAndAutomatic_Activity.this.startActivity(configure);
    }

}

【问题讨论】:

  • 您确定buttonAuthorizeUsersButtonondemandandautomatic_activity.xml 布局文件中的有效ID?
  • 您在 logcat 中遇到的错误是什么?
  • 啊哈!就是这样,谢谢。这是一个有效的按钮名称,但它不是我认为的按钮。因此,标识符被识别(斜体字)这一事实让我感到自满,因为它在 R.java 文件中 - 但是,对于另一个 Activity。

标签: android android-emulator android-intent android-widget android-button


【解决方案1】:

导致崩溃的不是按钮单击。由于设置侦听器是导致崩溃的原因,因此buttonAuthorizeUsers 必须为 null,如果您在 null 对象上调用方法,则会发生崩溃。

【讨论】:

  • 我不明白它怎么可能是空的。它在相应的 xml 文件中:
  • @ClayShannon,这是描述布局的 xml。要在代码中实际获取对该按钮的引用,您需要 findViewById,如果 R.id 类不包含此类 id,则该按钮将为 null。
  • @ClayShannon 请注意,在您的 xml 中,您为它提供了 configure_button 的 ID,但在您的代码中,您尝试将其检索为 buttonAuthorizeUsers
  • 查看stackoverflow.com/questions/9106659/activity-refuses-to-start/… 中的自动回答 我忘记将第二个活动添加到清单中!
猜你喜欢
  • 2020-01-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-12-15
相关资源
最近更新 更多