Android 如何在非活动类中找到视图?
我想在非活动类中找到一个ToggleButton,但得到了一个nullpointerException。我喜欢下面的代码:Android 如何在非活动类中找到视图?,android,Android,我想在非活动类中找到一个ToggleButton,但得到了一个nullpointerException。我喜欢下面的代码: public class ClassMode{ public static boolean isClassMode(Context c) { ToggleButton t = new ToggleButton(c); t = (ToggleButton) t.findViewById(R.id.classmode); if (t.isChec
public class ClassMode{
public static boolean isClassMode(Context c) {
ToggleButton t = new ToggleButton(c);
t = (ToggleButton) t.findViewById(R.id.classmode);
if (t.isChecked()) {
return true;
} else {
return false;
}
}
public static void setNextMode(final Context context){
if(isClassMode){
dosomething();
}
}
}
我做错什么了吗?我是一个新的程序员,我想这个问题可能没什么,但对我来说恰恰相反。
谁来帮帮我!期待您的回复。
3Q
findViewById
将在调用它的对象中找到一个视图。通常在活动中调用,但也可以在任何具有子项的视图组中调用
在您的案例中,您可以在按钮
对象上调用它。我怀疑此按钮是否包含id为R.id.classmode
的子项
尝试:
(注意:您应该发布一个带有实际异常的日志,否则我们只是猜测)更改行
t = (ToggleButton) t.findViewById(R.id.classmode);
到
请发布LogCat摘录,它显示了如此多的例外情况。我可能知道原因。
t = (ToggleButton) t.findViewById(R.id.classmode);
t = (ToggleButton) findViewById(R.id.classmode);