문제

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();

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?

도움이 되었습니까?

해결책

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.

다른 팁

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

If you are doing it before the setContentView() method call, then the values will be null.

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();
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);

Place the following after the setContentView() method.

final EditText edit =  (EditText) findViewById(R.id.Your_Edit_ID);
String emailString = (String) edit.getText().toString();
Log.d("email",emailString);
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top