我正在开发一个AlertDialog,它应该显示一个包含图像和文本的大小为2的列表。但是我无法让它发挥作用。
我按照这个链接
Icons in a List dialog
当我放置getActivity()时,它没有认识到帖子的建议我把getApplicationContext();
public MainActivity extends Activity{
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_complaint);
cameraButton = (ImageView) findViewById(R.id.cmp_camera);
cameraButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View arg0) {
final String[] items = new String[]{"From Gallery", "From Camera"};
final Integer[] icons = new Integer[]{R.drawable.ic_launcher, R.drawable.ic_drawer};
ListAdapter adapter = new CameraPickAdapter(getApplicationContext(), items, icons);
new AlertDialog.Builder(getApplicationContext()).setTitle("Select Image")
.setAdapter(adapter, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int item) {
Toast.makeText(getApplicationContext(), "Item Selected: " + item, Toast.LENGTH_SHORT).show();
}
}).show();
}
});
}
}
以下代码是Adapter类
CameraPickAdapter
public class CameraPickAdapter extends ArrayAdapter<String> {
private List<Integer> images;
public CameraPickAdapter(Context context, List<String> items, List<Integer> images) {
super(context, android.R.layout.select_dialog_item, items);
this.images = images;
}
public CameraPickAdapter(Context context, String[] items, Integer[] images) {
super(context, android.R.layout.select_dialog_item, items);
this.images = Arrays.asList(images);
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
View view = super.getView(position, convertView, parent);
TextView textView = (TextView) view.findViewById(android.R.id.text1);
textView.setCompoundDrawablesWithIntrinsicBounds(images.get(position), 0, 0, 0);
textView.setCompoundDrawablePadding(
(int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 12, getContext().getResources().getDisplayMetrics()));
return view;
}
}
我不知道为什么我没有得到。我认为这很简单,但我发现它很难破解
答案 0 :(得分:2)
将getApplicationContext()
更改为MainActivity.this
,即更改
new AlertDialog.Builder(getApplicationContext()).setTitle("Select Image")
.setAdapter(adapter, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int item) {
Toast.makeText(getApplicationContext(), "Item Selected: " + item, Toast.LENGTH_SHORT).show();
}
}).show();
到
new AlertDialog.Builder(MainActivity.this).setTitle("Select Image")
.setAdapter(adapter, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int item) {
Toast.makeText(MainActivity.this, "Item Selected: " + item, Toast.LENGTH_SHORT).show();
}
}).show();
答案 1 :(得分:1)
这样做 -
new AlertDialog.Builder(MainActivity.this)
它可能适合你。
答案 2 :(得分:0)
在尝试在 AlertDialog 上应用自定义布局之前,我遇到了同样的问题,当我将其更改为对话时效果很好请查看我的{{3 }}