【问题标题】:Android: How can I reference layout items outside the Main Activity?Android:如何在 Main Activity 之外引用布局项?
【发布时间】:2013-05-16 21:26:00
【问题描述】:

我的 onCreate 方法设置内容视图并设置图像按钮:

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    ImageButton mGetClickTime = (ImageButton) findViewById(R.id.clicker);

}

但我想创建一个改变 ImageButton 背景的方法:

public void mUpdateBackground() {
if (backgroundPic) {
    randomImageId = R.drawable.bg1;
}
else {
    randomImageId = R.drawable.bg0;
}
mGetClickTime.setImageResource(randomImageId);
}

问题是,mUpdateBackground 方法不知道布局。如果我在方法中声明布局,它会重置 MainActivity 中以编程方式所做的所有更改。

有什么办法可以解决这个问题吗?

【问题讨论】:

    标签: android layout methods imagebutton


    【解决方案1】:

    mUpdateBackground 方法不知道布局

    我将把它翻译为:

    mUpdateBackground 方法不知道 ImageButton

    如果正确,请将ImageButton mGetClickTime 设为您的活动的数据成员,而不是onCreate() 中的局部变量,并让mUpdateBackground() 成为同一活动的方法。

    【讨论】:

    • 感谢您的帮助。我已经尝试过了,但是 mUpdateBackground 方法中的 mGetClickTime 显示为 null,即使 onCreate 中的那个显示为正确分配。有什么想法吗?
    • 对不起,我刚刚重读了一遍。您的意思是在定义类之后但在 onCreate 之前设置 ImageButton mGetClickTime?这是否使它成为一个字段变量?
    • 我明白了。问题是我忘记更改 ImageButton mGetClickTime = (ImageButton) findViewById(R.id.clicker); to mGetClickTime = (ImageButton) findViewById(R.id.clicker);
    【解决方案2】:

    您需要将 ImageButton 声明移动到您的 Activity 范围,而不是您的 onCreate() 方法范围。试试这样:

    public class YourActivity extends Activity{
        ImageButton mGetClickTime;
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
            mGetClickTime = (ImageButton) findViewById(R.id.clicker);
        }
    
    
        public void mUpdateBackground() {
            if (backgroundPic) {
                randomImageId = R.drawable.bg1;
            }
            else {
                randomImageId = R.drawable.bg0;
            }
            mGetClickTime.setImageResource(randomImageId);
        }
    }
    

    【讨论】:

    • 感谢您的帮助。我已经尝试过了,但是 mUpdateBackground 方法中的 mGetClickTime 显示为 null,即使 onCreate 中的那个显示为正确分配。有什么想法吗?
    • 已经知道了。问题是我忘记更改 ImageButton mGetClickTime = (ImageButton) findViewById(R.id.clicker);到 mGetClickTime = (ImageButton) findViewById(R.id.clicker);非常感谢
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-07-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多