【问题标题】:Android 2.3.3, Eclipse - unable to use button after switching to other layout pagesAndroid 2.3.3, Eclipse - 切换到其他布局页面后无法使用按钮
【发布时间】:2012-02-22 19:44:52
【问题描述】:

概述: 我的程序中有两页;主页和其他页面。

在主页上我有两个按钮;一个按钮切换到另一页,添加按钮将一些值添加在一起。

在另一个页面上,我有一个按钮可以让我回到主页。

目前我可以毫无问题地在两个页面之间切换。

我的问题: 当我第一次打开程序时,我可以单击“添加”按钮,它会将值添加在一起。我可以继续在两个页面之间切换而不会出现问题。 但是,在我切换页面后,当我点击添加按钮时,我的程序崩溃了。

这是我的 java 文件。

    package com.test;
    import android.app.Activity;
    import android.os.Bundle;
    import android.view.View;
    import android.view.View.OnClickListener;
    import android.widget.*;

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

    Button enterScoreButton = (Button) findViewById(R.id.button1);
    enterScoreButton.setOnClickListener(enterScoreButtonListener);
}

public OnClickListener enterScoreButtonListener = new OnClickListener() 
{
    @Override
    public void onClick(View v1) 
    {
    }

    public int addEntireHole(int addedHoles) {
        return (addedHoles);
    }
};

//This section goes from the main page to the other page
public OnClickListener Startpage = new OnClickListener(){
    public void onClick(View v2){
    }
};

public void onCreate(View view){
    Button buttonSwitchMain = (Button)findViewById(R.id.btnSwitch);
    buttonSwitchMain.setOnClickListener(Startpage);
    setContentView(R.layout.other);
 }

//This section goes from the other page to the main page

public OnClickListener otherpage = new OnClickListener(){
    public void onClick(View v3){
    }
};


public void onCreate3(View view2){
    Button buttontoMain = (Button)findViewById(R.id.btnBack);
    buttontoMain.setOnClickListener(otherpage);
    setContentView(R.layout.main);
 }

}

【问题讨论】:

    标签: android eclipse button


    【解决方案1】:

    在你的方法onCreate3中,在调用setContentView之后你应该调用

    enterScoreButton.setOnClickListener(enterScoreButtonListener);
    

    再一次。

    【讨论】:

    • 感谢您的回复和建议。我尝试了您的建议,但 enterScoreButton 似乎超出了范围。所以然后我在它之前添加了 Button enterScoreButton = (Button) findViewById(R.id.button1) 它让我编译和运行它并没有出现任何错误,但它似乎也没有在按下后执行任何代码输入按钮...
    • 嗯,这是我之前想知道的。当您单击按钮时,将调用侦听器的 onClick 方法 - 但您的方法不包含任何代码。请尝试添加行 Log.v("","CLICKED");并查看单击按钮时 LogCat 是否显示消息。
    • 上面的例子是我的主程序的简化版;我试图将其简化为仅最基本的必需品。我以前不知道如何使用 Log.v,但发现它真的很有用。当我将 Log.v 放入 onClick 时,它确实显示在 LogCat 中。我尝试然后将它 Log.v 复制到代码的 addEntireHole 部分,但它从未被执行。我的印象(可能是错误的)因为代码是 enterScoreButtonListener 的一部分,所以它里面的所有东西都会被执行。
    【解决方案2】:

    我建议你使用意图切换页面,来解决这个问题。

    【讨论】:

    • 我刚学,用intent切换页面有什么好处?
    猜你喜欢
    • 1970-01-01
    • 2021-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-08-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多