gpt4 book ai didi

java - 从另一个类访问 Activity 中的 UI 元素

转载 作者:行者123 更新时间:2023-11-30 11:44:29 24 4
gpt4 key购买 nike

我的代码有问题

setContentView(R.layout.game);
TextView text = (TextView) findViewById(R.id.qwe_string);
text.setText("Hello Android");

如果它在一个 Activity 中,它会工作,但如果不是,很明显,它会给出错误:

The method findViewById(int) is undefined for the type new TimerTask(){}
The method setContentView(int) is undefined for the type new TimerTask(){}

代码在单独类(不是 Activity )中的计时器内。完整代码如下。

//main timer task for ingame time processing
static Timer gameTimer = new Timer();
static TimerTask gameTimerTask = new TimerTask() {
@Override
public void run() {
setContentView(R.layout.game);
TextView text = (TextView) findViewById(R.id.qwe_string);
text.setText("Hello Android");
}
};

我试过这样改

ScreenGame.this.setContentView(R.layout.game);
TextView text = (TextView) ScreenGame.this.findViewById(R.id.qwe_string);
text.setText("Hello Android");

但是还是不行:(

PS - 是的,我搜索了其他类似的问题,但它们虽然看起来相同,但实际上完全不同。

最佳答案

ScreenGame.this.setContentView(R.layout.game);
TextView text = (TextView) ScreenGame.this.findViewById(R.id.qwe_string);
text.setText("Hello Android");

完全一样

setContentView(R.layout.game);
TextView text = (TextView) findViewById(R.id.qwe_string);
text.setText("Hello Android");

代码错误

您应该创建一个父类,它会触发所有其他 Activity。在那个父类中,您可以引用每个子 Activity ,并且可以向每个 child 询问它的文本字段:

// In the parent:
child.getTextView().setText("Hello galaxy!");

// with the child method:
TextView getTextView () {
return (TextView) findViewById(R.id.qwe_string);
}

编辑:更多信息:

我给的代码不好,我没有很好地理解你的问题......我希望我现在明白了,我会努力纠正自己。

创建一个单独的类,例如 MyTimer,它将扩展 TimerTask 类:

class MyTimer extends TimerTask {
// your class
}

创建一个构造函数,除了一个 TextView 作为参数,并保存对它的引用。

TextView theTextView;
MyTimer (TextView tv) {
this.theTextView = tv;
}

现在执行run():

@Override
public void run() {
setContentView(R.layout.game);
thetextView.setText("Hello Galaxy!");
}

使用下面的代码调用这个类:

static TimerTask gameTimerTask = new MyTimer((TextView) findViewById(R.id.qwe_string));

我希望这一切都是正确的,因为我没有任何测试环境,所以我必须凭内存来做。至少它应该能帮助您朝着正确的方向前进。

关于java - 从另一个类访问 Activity 中的 UI 元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10765302/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com