Created
December 8, 2017 08:38
-
-
Save vejei/5ac9cdcf8d0a8af5bc91a779a9c324b7 to your computer and use it in GitHub Desktop.
Add icon for AlertDialog item
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import android.content.DialogInterface; | |
import android.content.Intent; | |
import android.support.v4.app.Fragment; | |
import android.support.v7.app.AlertDialog; | |
import android.view.View; | |
import android.view.ViewGroup; | |
import android.widget.ArrayAdapter; | |
import android.widget.ImageView; | |
import android.widget.ListAdapter; | |
import android.widget.TextView; | |
public class MyFragment extends Fragment implements View.OnClickListener { | |
@Override | |
public void onClick(View v) { | |
switch (v.getId()) { | |
case R.id.button: | |
final Item[] items = { | |
new Item("Take Photo", android.R.drawable.ic_photo_camera), | |
new Item("Select Image", android.R.drawable.ic_image), | |
new Item("...", 0),//no icon for this one | |
}; | |
ListAdapter adapter = new ArrayAdapter<Item>(this, | |
android.R.layout.select_dialog_item, | |
android.R.id.text1, | |
items){ | |
public View getView(int position, View convertView, ViewGroup parent) { | |
//Use super class to create the View | |
View view = super.getView(position, convertView, parent); | |
TextView tv = (TextView)v.findViewById(android.R.id.text1); | |
//Put the image on the TextView | |
tv.setCompoundDrawablesWithIntrinsicBounds(items[position].icon, 0, 0, 0); | |
//Add margin between image and text (support various screen densities) | |
int dp5 = (int) (5 * getResources().getDisplayMetrics().density + 0.5f); | |
tv.setCompoundDrawablePadding(dp5); | |
return view; | |
} | |
}; | |
AlertDialog.Builder builder = new AlertDialog.Builder(activity); | |
builder.setAdapter(adapter, new DialogInterface.OnClickListener() { | |
@Override | |
public void onClick(DialogInterface dialog, int which) { | |
if (items[which].equals(items[0])) { | |
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE); | |
startActivityForResult(intent, 1); | |
} else if (items[which].equals(items[1])) { | |
Intent intent = new Intent(Intent.ACTION_PICK, | |
MediaStore.Images.Media.EXTERNAL_CONTENT_URI); | |
startActivityForResult(intent, 2); | |
} | |
} | |
}); | |
builder.show(); | |
break; | |
} | |
} | |
public static class Item{ | |
public final String text; | |
public final int icon; | |
public Item(String text, Integer icon) { | |
this.text = text; | |
this.icon = icon; | |
} | |
@Override | |
public String toString() { | |
return text; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment