好的,好吧,我试图制作一个自定义微调器,只使用图像。我在一个值文件夹中的.xml文件上定义了一个数组,其中有图像项作为资源。 我想用这个图像填充一个微调器.. 以下是我到目前为止所做的一切:
在res / drawable-mdpi
我有以下图片:
remove_minus_circle_black.png
remove_minus_circle_red.png
remove_minus_sign.png
remove_minus_sign2.png
remove_minus_sign3.png
在res / values / arrays.xml
<?xml version="1.0" encoding="utf-8"?>
<resources>
<array name="minusIcons">
<item>@drawable/remove_minus_circle_black</item>
<item>@drawable/remove_minus_circle_red</item>
<item>@drawable/remove_minus_sign</item>
<item>@drawable/remove_minus_sign2</item>
<item>@drawable/remove_minus_sign3</item>
</array>
<array name="directionIcons">
</array>
</resources>
在res / layout / row.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="wrap_content"
android:orientation="horizontal">
<ImageView
android:id="@+id/icon"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
/>
</LinearLayout>
现在代码(活动本身)我尝试使用自定义适配器将图像添加到微调器:
public class Definicoes extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_definicoes);
Spinner spinner = (Spinner) findViewById(R.id.minusSpinner);
int[] array = getResources().getIntArray(R.array.minusIcons);
String [] objects = new String[array.length];
for(int i = 0; i != array.length; i++){
objects[i] = "" + array[i];
}
spinner.setAdapter(new MyAdapter(Definicoes.this, R.id.minusSpinner, objects));
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.definicoes, menu);
return true;
}
class MyAdapter extends ArrayAdapter<String>{
String[] objects;
public MyAdapter(Context context, int textViewResourceId, String[] objects) {
super(context, textViewResourceId, objects);
this.objects = objects;
}
@Override
public View getDropDownView(int position, View convertView,ViewGroup parent) {
return getCustomView(position, convertView, parent);
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
return getCustomView(position, convertView, parent);
}
public View getCustomView(int position, View convertView, ViewGroup parent) {
LayoutInflater inflater=getLayoutInflater();
View row=inflater.inflate(R.layout.row, parent, false);
ImageView icon = (ImageView) row.findViewById(R.id.icon);
icon.setImageResource(Integer.parseInt(objects[position]));
return row;
}
}
}
问题/错误:我打开活动,然后点击微调器,它没有任何东西! 非常感谢你们!我想我可能做错了什么,从未使用自定义适配器......
答案 0 :(得分:4)
使用此方法找到解决方案:
ImageView icon = (ImageView) row.findViewById(R.id.icon);
TypedArray imgs = getResources().obtainTypedArray(R.array.minusIcons);
icon.setImageResource(imgs.getResourceId(position, -1));
将数组类型更改为字符串数组,它可以工作:P