I am making an android program. In my app, I am using a single choice selection AlertDialog whose items are added programmatically. What I want to do is:
Here is what I have:XML:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:paddingTop="5dp" >
<Button
android:id="@+id/selectDateButton"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Please, select date" />
</LinearLayout>
JAVA:
public class ExperimentListView extends Activity {
private static final DateFormat DATE_FORMAT = new SimpleDateFormat("yyyy-MM-dd");
private static Calendar calendar = Calendar.getInstance();
private static Button selectDateButton;
private static String[] items;
private static int selectedDatePosition = 0;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.list_view_ex);
selectDateButton = (Button)findViewById(R.id.selectDateButton);
selectDateButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
items = new String[20];
for (int i = 0; i < 20; i++) {
items[i] = DATE_FORMAT.format(calendar.getTime());
calendar.add(Calendar.DATE, 1);
}
showListView();
}
});
}
private void showListView() {
AlertDialog.Builder builder = new AlertDialog.Builder(ExperimentListView.this);
builder.setTitle("Select date");
builder.setItems(items, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
selectedDatePosition = which;
selectDateButton.setText(items[selectedDatePosition]);
}
});
AlertDialog alertDialog = builder.create();
alertDialog.getListView().setSelection(selectedDatePosition);
alertDialog.show();
}
}
I haven't been able to find a solution to this so far and I would be grateful if someone can help. Thanks in advance.
Instead of using builder.setItem
use builder.setSingleChoiceItems
with selected item position passed as an argumet like
builder.setSingleChoiceItems(strArray, selected_pos, new DialogInterface.OnClickListener ()
{
@Override
public void onClick(DialogInterface dialog, int which)
{
}
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With