Android input return value

I pull my hair on top of it.

I have an application that when you click on a menu item, I want it to display an input dialog. When the user clicks “OK”, the text they entered in the EditText in the dialog box should be returned for use later in the activity.

So, I thought about putting:

name = input.getText().toString(); //input is an EditView which is the setView() of the dialog 

Inside onClick, the "Ok" button will work, but it is not. Eclipse tells me that I cannot set the name inside onClick because it is not final, but if I change the name definition to final, it cannot be changed explicitly and therefore cannot be set inside onClick ().

Here is the complete code for this bit:

 String routeName = ""; AlertDialog.Builder alert = new AlertDialog.Builder(this); alert.setTitle("Title"); alert.setMessage("Message"); // Set an EditText view to get user input final EditText inputName = new EditText(this); alert.setView(inputName); alert.setPositiveButton("Set Route Name", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { routeName = inputName.getText().toString(); } }); alert.show(); 

I have to do something really stupid here, because I searched for many years and did not find anyone else with the same problem.

Can anyone enlighten me?

Thank you for your time,

Infinitifizz

+7
source share
2 answers

In fact, you cannot reach anything in your onlcick, which I assume is an anonymous function. What you can do is get context and find your views from there. It will look something like this:

 yourButton.setOnClickListener(new View.OnClickListener() { public boolean onClick(View v) { name = findViewById(R.id.yourInputId)).getText().toString(); return true; } ); 

You can also use the v argument for instace by calling v.getContext() in your listener.

+3
source

You can make routerName member variable.

+2
source

All Articles