gpt4 book ai didi

java - 使用单独的类时 findViewById() 不起作用

转载 作者:行者123 更新时间:2023-11-29 07:42:25 25 4
gpt4 key购买 nike

嗨,我是 Android 新手

我想将以下代码与我的 MainActivity 文件分开保存。但是,当我尝试在单独的类中查找 findViewById() 时,出现错误

"cannot be resolved"

现在我知道我不能扩展 MainActivity 类,因为它会导致堆栈溢出,但有人能告诉我如何从这个单独的文件访问 TextView 吗?

public class Counter {

private TextView tempTextView;
//Temporary TextView
private Button tempBtn;
public Handler mHandler = new Handler();
public long startTime;
public long elapsedTime;
public final int REFRESH_RATE = 100;
public String hours,minutes,seconds,milliseconds;
public long secs,mins,hrs,msecs;
public boolean stopped = false;

public Runnable startTimer = new Runnable() {
public void run() {
elapsedTime = System.currentTimeMillis() - startTime;
updateTimer(elapsedTime);
mHandler.postDelayed(this,REFRESH_RATE);
}
};


private void updateTimer (float time) {
secs = (long) (time / 1000);
mins = (long) ((time / 1000) / 60);
hrs = (long) (((time / 1000) / 60) / 60); /* Convert the seconds to String * and format to ensure it has * a leading zero when required */
secs = secs % 60;
seconds = String.valueOf(secs);
if (secs == 0) {
seconds = "00";
}
if (secs < 10 && secs > 0) {
seconds = "0" + seconds;
} /* Convert the minutes to String and format the String */
mins = mins % 60;
minutes = String.valueOf(mins);
if (mins == 0) {
minutes = "00";
}
if (
mins < 10 && mins > 0
) {
minutes = "0" + minutes;
} /* Convert the hours to String and format the String */
hours = String.valueOf(hrs);
if (hrs == 0) {
hours = "00";
}
if (hrs < 10 && hrs > 0) {
hours = "0" + hours;
}
/* Although we are not using milliseconds on the timer in this example * I included the code in the event that you wanted to include it on your own */
milliseconds = String.valueOf((long) time);
if (milliseconds.length() == 2) {
milliseconds = "0" + milliseconds;
}
if (milliseconds.length() <= 1) {
milliseconds = "00";
}
milliseconds = milliseconds.substring(milliseconds.length() - 3, milliseconds.length() - 2);
/* Setting the timer text to the elapsed time */
// ((TextView) findViewById(R.id.elapsed_value)).setText(hours + ":" + minutes + ":" + seconds);
// ((TextView)findViewById(R.id.timerMs)).setText("." + milliseconds); }

}
}

最佳答案

您需要扩充 View 并从该 View 调用方法 findViewById()。要膨胀 View ,您需要一个上下文(您可以在自定义构造函数中设置它)

View view; 
LayoutInflater inflater = (LayoutInflater) yourContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
view = inflater.inflate(R.layout.mylayout, null);

tempTextView = (TextView) view.findViewById(R.id.tv);

关于java - 使用单独的类时 findViewById() 不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28821018/

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