問題描述
這個問題很簡單.但我想知道我們究竟在哪里引用了 gui 元素?至于在哪里定義最好:
The question is quite simple. But I want to know where exactly do we make our references to the gui elements? As in which is the best place to define:
final EditText edit = (EditText) findViewById(R.id.text_xyz);
edit.getText.tostring();
當我在默認的 oncreate() 中嘗試它時,我得到空值.因此,為了獲得最佳實踐,您是否推薦一個單獨的類來引用 main.xml 中這些已定義的 gui 元素.從這里我們可以調用這些元素的各種方法,比如gettext或settext?
When I try it doing inside the default oncreate() I get null values. So for best practice, do u recommend a separate class for referring these already defined gui elements in main.xml. From here we can call various methods of these elements like gettext or settext?
推薦答案
好吧,這取決于您的需求.我經常在活動中保留對小部件的引用(作為類字段) - 并將它們設置在 onCreate
方法中.我認為這是個好主意
您的空值的原因可能是您嘗試在 onCreate()
方法中設置 contentView()
之前調用 findViewById()
-請檢查一下.
Well, it depends on your needs. Very often I keep my references to widgets in activity (as a class fields) - and set them in onCreate
method. I think that is a good idea
Probably the reason for your nulls is that you are trying to call findViewById()
before you set contentView()
in your onCreate()
method - please check that.
這篇關于如何從 EditText 獲取文本?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!