Reputation: 17
i just created an alert dialog with multiple item. I set text in each items with values of string.xml but not showing corect value.
here is the code:
private void showImageImportDialog() {
String[] items = new String[]{String.valueOf(R.string.open_camera), String.valueOf(R.string.open_gallery)};
AlertDialog.Builder dialog = new AlertDialog.Builder(this);
dialog.setTitle(R.string.select_image);
dialog.setItems(items, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
if (which == 0){
......
}
if (which == 1) {
......
}
}
});
dialog.create().show();
}
string.xml
<resources>
<string name="open_camera">Camera</string>
<string name="open_gallery">Gallery</string>
<string name="select_image">Select Image</string>
Upvotes: 0
Views: 228
Reputation: 1987
You're doing many things wrong. First, you can declare your array in the string resources. I have rewrites your code to make it work.
Copy below code and paste it in your string resources file(e.g res/string.xml
)
<string-array name="titles">
<item>Camera</item>
<item>Gallery</item>
<item>Select Image</item>
</string-array>
Then, replace your java code with the following.
private void showImageImportDialog() {
String[] items = getResources().getStringArray(R.array.titles);
AlertDialog.Builder dialog = new AlertDialog.Builder(this);
dialog.setTitle(items[2]);
dialog.setItems(items, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
}
});
dialog.create().show();
}
It should work now.
Upvotes: 0
Reputation: 49
Correct form to get string from xml is
getString(R.string.select_image)
example:
dialog.setTitle(getString(R.string.select_image));
Upvotes: 0
Reputation: 11035
String.valueOf(R.string.open_camera)
is not how to get a text from a resource id in Android. You have to use getString(R.string.open_camera)
for that.
Upvotes: 1