这是示例代码,您可以参考this并查看自定义布局如何膨胀以及您做错了什么。希望能帮助到你:
public class Style extends Activity{
String[] items = { "bangladesh", "bangla", "bd", "australia", "japan",
"china", "indiaA", "indiaC" };
String[] images = { "R.drawable.ic_launcher", "R.drawable.ic_launcher",
"R.drawable.ic_launcher", "R.drawable.ic_launcher",
"R.drawable.ic_launcher", "R.drawable.ic_launcher",
"R.drawable.ic_launcher","R.drawable.ic_launcher" };
Spinner spin;
TextView txt1;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.npicker);
initcomponents();
actionlistener();
CustomAdapter spinneradapter = new CustomAdapter(this,
android.R.layout.simple_spinner_item, items,images);
spinneradapter
.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spin.setAdapter(spinneradapter);
}
private void actionlistener() {
}
private void initcomponents() {
spin = (Spinner) findViewById(R.id.npicker_spnr);
}
public class CustomAdapter extends ArrayAdapter<String> {
String[] items,images;
Context context;
int rid;
TextView textview;
ImageView imageview;
LayoutInflater inflater;
public CustomAdapter(Context context, int rid, String[] items,String[] images) {
super(context, rid, items);
this.items = items;
this.context = context;
this.rid = rid;
this.images=images;
inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
public int getCount() {
return items.length;
}
@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) {
if (convertview == null) {
convertview = inflater.inflate(R.layout.spinneritems, parent, false);
textview = (TextView) convertview
.findViewById(R.id.spinneritem_txt);
imageview = (ImageView) convertview
.findViewById(R.id.spinneritem_iv);
imageview.setBackgroundResource(R.drawable.ic_launcher);
textview.setText(items[position]);
}
return convertview;
}
}
}
这是微调器项 xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal" >
<ImageView
android:id="@+id/spinneritem_iv"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="@drawable/ic_launcher" />
<TextView
android:id="@+id/spinneritem_txt"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="center_vertical"
android:text="Hello i am android logo" />
</LinearLayout>