[英]Global Reference findViewById
Is it possible to get a reference to an XML element such as a button using findViewById globally in the main java class? 是否可以在主java类中全局使用findViewById来获取对XML元素(例如按钮)的引用?
I have so many references that I need to keep on calling them all over again multiple times because I can't use the reference I called in the onCreate method. 我有太多的引用,因此我需要多次重复调用它们,因为我无法使用在onCreate方法中调用的引用。
private long mode;
private final Button playBtn = (Button)findViewById(R.id.playBtn);
private final TextView aboutTitle = (TextView)findViewById(R.id.aboutTitle);
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
playBtn.setTypeface(robotoThin);
aboutTitle.setText("hello world");
}
I know that to fix the error would be to reference the button and the textview after the setContentView but the problem is that I need to repeat all my references for each method in the same class. 我知道要解决该错误,将在setContentView之后引用按钮和textview,但是问题是我需要为同一类中的每个方法重复所有引用。
// try this way (here i'm declare your both view object as globaly for your class so it can be acccess any where in classs and is created onCreate() at first time and further it used directly)
private long mode;
private Button playBtn;
private TextView aboutTitle;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
playBtn = (Button)findViewById(R.id.playBtn);
aboutTitle = (TextView)findViewById(R.id.aboutTitle);
playBtn.setTypeface(robotoThin);
aboutTitle.setText("hello world");
}
You have to create member variables for the Views
you want to reference and you initialize them in onCreate()
once. 您必须为要引用的
Views
创建成员变量,然后在onCreate()
一次初始化。 Then you reference these variables where you need inside the Activity
然后在“
Activity
需要的地方引用这些变量
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.