To summarize, I made a custom layout for my dialog box, and there is an EditText inside it, from which I want to capture entered information. But I am not sure how to both:
1) instantiate a "new" EditText (to prevent null exception), AND
2) associate this new EditText with its ID in the layout (R.id.edit_name) so android knows to get info from the EditText INSIDE the dialogbox
The 4 lines of COMMENTED code is where I'm not sure which ones to use...
Any help is appreciated, thanks!
public class MainActivity extends AppCompatActivity {
private Button button;
private Context context = this;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.content_inventory);
}
public void onClickAddItem(View view) {
final Dialog dialog = new Dialog(this);
dialog.setContentView(R.layout.dialog_layout);
// final EditText nameInput = new EditText(this);
// nameInput.findViewById(R.id.edit_name);
// EditText nameInput = new EditText(context);
// final EditText nameInput = (EditText)findViewById(R.id.edit_name);
final LinearLayout wholelist = (LinearLayout) findViewById (R.id.wholelist);
button = (Button) findViewById(R.id.Adder);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Button OKbutton = (Button) dialog.findViewById(R.id.OK);
OKbutton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
wholelist.addView(createNewTextView(nameInput.getText().toString()));
dialog.dismiss();
}
});
dialog.show();
}
});
}
private TextView createNewTextView(String text) {
final TextView textView = new TextView(this);
textView.setText(text);
return textView;
}
}
Define your edit text as a global variable (out side your functions), so that you can use it where ever you want. Then initialize (introduce) it inside the onCreate
function.
EditText nameInput; // define your edit text
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.content_inventory);
nameInput = (EditText) findViewById(R.id.edit_name); // initialize your edit text
.
.
.
nameInput.getText().toString() // get data inside your edit text
When ever you need to read the information inside it just use this: nameInput.getText().toString()
to read the data in it.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.