Android 如何从 EditText 获取文本?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1974489/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to get text from EditText?
提问by Bohemian
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:
问题很简单。但我想知道我们究竟在哪里引用 gui 元素?定义的最佳位置是:
final EditText edit = (EditText) findViewById(R.id.text_xyz);
edit.getText.tostring();
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() 中尝试它时,我得到空值。因此,对于最佳实践,您是否建议使用一个单独的类来引用 main.xml 中这些已定义的 gui 元素。从这里我们可以调用这些元素的各种方法,如 gettext 或 settext?
采纳答案by Ramps
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.
嗯,这取决于您的需求。我经常在活动中保留对小部件的引用(作为类字段) - 并在onCreate
方法中设置它们。我认为这是一个好主意,
也许你空的理由是,你试图调用findViewById()
您之前设置contentView()
你的onCreate()
方法-请检查。
回答by Jason
The quickest solution to your problem I believe is that you simply are missing parentheses on your getText
. Simply add ()
to edit.getText().toString()
and that should solve it
我相信解决您的问题的最快方法是您只是缺少getText
. 只需添加()
即可edit.getText().toString()
解决它
回答by Ryan Alford
If you are doing it before the setContentView()
method call, then the values will be null.
如果您在setContentView()
方法调用之前执行此操作,则值将为空。
This will result in null:
这将导致空值:
super.onCreate(savedInstanceState);
Button btn = (Button)findViewById(R.id.btnAddContacts);
String text = (String) btn.getText();
setContentView(R.layout.main_contacts);
while this will work fine:
虽然这会正常工作:
super.onCreate(savedInstanceState);
setContentView(R.layout.main_contacts);
Button btn = (Button)findViewById(R.id.btnAddContacts);
String text = (String) btn.getText();
回答by Yaser Balaghi
String fname = ((EditText)findViewById(R.id.txtFirstName)).getText().toString();
String lname = ((EditText)findViewById(R.id.txtLastName)).getText().toString();
((EditText)findViewById(R.id.txtFullName)).setText(fname + " "+lname);
回答by Trianna Brannon
Place the following after the setContentView() method.
将以下内容放在 setContentView() 方法之后。
final EditText edit = (EditText) findViewById(R.id.Your_Edit_ID);
String emailString = (String) edit.getText().toString();
Log.d("email",emailString);