I am trying to make a reusable UI class. I admit that I don’t understand how it should work. I want to have a class that I pass arguments into and when the user makes a selection it will return the selected value. This will actually be a more complex, custom dialog that will be used. For testing, I put together the following code from examples I found and it does everything but return the selected value back.
So, how can I get the user selected value back in the main routine?
Main module
package com.mine.zd;
import android.app.Activity;
import android.content.DialogInterface;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
public class ZDialogActivity extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button btn1 = (Button) findViewById(R.id.btn1);
btn1.setOnClickListener(new View.OnClickListener(){
@Override
public void onClick(View arg0){
go();
}
});
}
private void go()
{
final String[] vOptions = { "One", "Two", "Three" } ;
myOptions.getmenuOptions(
ZDialogActivity.this, "Select Mode", vOptions,
new android.content.DialogInterface.OnClickListener(){
@Override
public void onClick(DialogInterface dialog, int which) {
Log.w("TEST", "which=" + which );
}
}
);
}
}
called module
package com.mine.zd;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.util.Log;
public class myOptions {
public static void getmenuOptions(Context context, String msg,
String[] vOptions, OnClickListener neutralClickListener){
new AlertDialog.Builder(context)
.setTitle("Select Mode")
.setItems(vOptions, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
Log.w("TEST", "item=" + whichButton );
dialog.dismiss();
}
})
.setNeutralButton("Cancel", neutralClickListener )
.create().show();
}
}
I do get the returned “cancel” button value of -3, but I need the id of the option selected.
Here how about this:
And your helper class:
1) Start your class names with uppercase
2) Dont use a static helper method, instantiate the class it’s better practice in this scenario
3) You can then pass the non changing fields to the constructor
4) Use an interface to send message between classes (your Activity acts as a Listener on the dialog onClick event)
5) Don’t use annoyomous onClick listeners let your class implement it and switch on the view id to pertain which was clicked
Hope that helps!