Get text from a textbox when a button is clicked


Basically, i have one Button and an EditText controls on activity. How to get value of the EditText to display in a message box when the button is clicked?

By sara asked on 2015-12-07
answer to this question

prakashgajera24
By prakashgajera24

Change to Edittext Object:

private EditText txtEdit;

private Button bt;

protected void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.activity_main);

txtEdit=(EditText)findViewById(R.id.txtEdit);

bt=(Button)findViewById(R.id.bt);

bt.setOnClickListener(new OnClickListener() {

@Override

public void onClick(View v) {

String txt=txtEdit.getText().toString();

Toast.makeText(MainActivity.this, txt, Toast.LENGTH_LONG).show();

}

});

}


2016-02-01 Reply

yuk.dara
By yuk.dara

Above the onCreate method of your activity, you declare two variables to hold references to EditText and Button. Then in the onCreate method, you create references to the controls and attach the button to click action using setOnClickListener method.
private EditText editText;
private Button bt;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
txtEdit=(EditText)findViewById(R.id.txtEdit);
bt=(Button)findViewById(R.id.bt);
bt.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
String txt=txtEdit.getText().toString();
Toast.makeText(MainActivity.this, txt, Toast.LENGTH_LONG).show();
}
});
}



2015-12-07 Reply





This website intents to provide free and high quality tutorials, examples, exercises and solutions, questions and answers of programming and scripting languages:
C, C++, C#, Java, VB.NET, Python, VBA,PHP & Mysql, SQL, JSP, ASP.NET,HTML, CSS, JQuery, JavaScript and other applications such as MS Excel, MS Access, and MS Word. However, we don't guarantee all things of the web are accurate. If you find any error, please report it then we will take actions to correct it as soon as possible.