I am learning how to create UI elements. I have created a few EditText input fields. On the click of a Button I want to capture the content typed into that input field.
By using getText():
Button mButton;
EditText mEdit;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
mButton = (Button)findViewById(R.id.button);
mEdit = (EditText)findViewById(R.id.edittext);
mButton.setOnClickListener(
new View.OnClickListener()
{
public void onClick(View view)
{
Log.v("EditText", mEdit.getText().toString());
}
});
}
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button rtn = (Button)findViewById(R.id.button);
EditText edit_text = (EditText)findViewById(R.id.edittext1);
rtn .setOnClickListener(
new View.OnClickListener()
{
public void onClick(View view)
{
Log.v("EditText value=", edit_text.getText().toString());
}
});
}
Try this code
final EditText editText = findViewById(R.id.name); // your edittext id in xml
Button submit = findViewById(R.id.submit_button); // your button id in xml
submit.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v)
{
String string = editText.getText().toString();
Toast.makeText(MainActivity.this, string, Toast.LENGTH_SHORT).show();
}
});
I guess you will have to use this code when calling the "mEdit" your EditText object :
myActivity.this.mEdit.getText().toString()
Just make sure that the compiler know which EditText
to call and use.
getText(editText);
getText(button);
getText(textView);
Just make method in your BaseActivity / create BaseActivity if you don't have.
public class BaseActivity extends AppCompatActivity{
public String getText(TextView tv) {
return tv.getText().toString().trim();
}
}
And extend your all activities by this BaseActivity.
public class YourActivity extends BaseActivity {
@Override
public void onCreate(Bundle savedInstanceState){
getText(editText);
getText(button);
getText(textView);
}
}
Note that EditText
, Button
extends TextView
, so I created only getText(TextView tv)
.
String value = YourEditText.getText().toString;