【问题标题】:Error with setOnClickListener(this)setOnClickListener(this) 出错
【发布时间】:2014-04-10 20:40:31
【问题描述】:

我使用了 Eclipse 默认创建的代码,并添加了一个带有 OnClickListener 的按钮。

以下代码在我使用 setOnClickListener(this) 的最后一行崩溃。

public class MainActivity extends Activity implements OnClickListener {

    private Button startStopButton;

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

        if (savedInstanceState == null) {
            getFragmentManager().beginTransaction()
                    .add(R.id.container, new PlaceholderFragment()).commit();
        }

        startStopButton = (Button) findViewById(R.id.startButton);
        startStopButton.setOnClickListener(this);
    }

这可能是微不足道的,但我不明白问题是什么。 onClick 方法在下面定义,如果它有任何相关性,但它现在什么都不做。

在布局 xml 中使用 onClick 有效,但我在其他地方读到使用它是不好的做法。

提前致谢!

【问题讨论】:

  • 肯定 startStopButton.setOnClickListener(this) 应该被替换..
  • Stacktraces 是你的朋友。
  • 我认为该按钮为空。你能检查按钮不为空吗?
  • 能否实现接口方法“onClick”?

标签: android onclicklistener


【解决方案1】:

问题是你正在加载一个片段

 if (savedInstanceState == null) {
            getFragmentManager().beginTransaction()
                    .add(R.id.container, new PlaceholderFragment()).commit();
        }

PlaceholderFragment() 中不存在startButton 的引用

 startStopButton = (Button) findViewById(R.id.startButton);

您的问题与此帖类似:

Unable to load url in webview (android)

【讨论】:

    【解决方案2】:

    尝试将行 implements OnClickListener 更改为 implements View.OnClickListener :-) 或者如我现在所见。 您确定按钮不在属于 PlaceHolderFragment 的 XML 布局文件中吗?

    【讨论】:

      【解决方案3】:

      startStopButton.setOnClickListener(this);
      替换为

      startStopButton.setOnClickListener(new View.OnClickListener() {
      
                  public void onClick(View arg0) {
                      // TODO Auto-generated method stub
                      Intent i=new Intent("com.monster.android.activitylifecycle.SecndActivity");
                      startActivity(i);
      
                  }
              });
      

      您正在传递 this 引用当前活动的对象..相反,您应该传递实现 onclick() 方法的匿名鼠标类 View.OnClickListener 的对象..

      【讨论】:

        【解决方案4】:

        请实现 onclick() 方法。

        public void onClick(View v){
                if(v.getId()==R.id.startButton)
        {
            //type what you want to do here
        }
        }
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2011-04-02
          相关资源
          最近更新 更多