2012-10-31 81 views
14

到spinner我要添加圖像spinner我曾嘗試這樣的:如何添加圖片中的Android

<Spinner 
    android:id="@+id/spinner1" 
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content" 
    android:background="@drawable/myImage" /> 

但有了這個代碼向下箭頭對微調的跡象變得不可見,請告訴我怎麼解決那個問題!我想要做的正是這樣的形象

enter image description here

+0

做什麼? –

+1

http://stackoverflow.com/questions/3609231/how-is-it-possible-to-create-a-spinner-with-images-instead-of-text –

回答

14

/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" 
    android:src="@drawable/icon"/> 
    <TextView 
    android:id="@+id/weekofday" 
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content"/> 
</LinearLayout> 

和Java的文件中添加此代碼

Spinner mySpinner = (Spinner)findViewById(R.id.spinner); 
    ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, 
    R.layout.row, R.id.weekofday, YourArrayHere); 
    mySpinner.setAdapter(adapter); 
+0

歡迎回來@ram很好的答案。 –

+0

謝謝@hardikjoshi –

+0

老兄,在哪裏(R.id.spinner定義? – Siddharth

5

在我來說,我剛使用標準佈局微調的項目,並覆蓋一點點一個ArrayAdapter。

private class PaymentTypeArrayAdapter extends ArrayAdapter<PaymentType> { 

    public PaymentTypeArrayAdapter(Context context) { 
     super(context, android.R.layout.simple_spinner_item); 

     addAll(PaymentType.getPaymentTypes()); 
    } 

    @Override 
    public View getView(int position, View convertView, ViewGroup parent) { 
     TextView label = (TextView) super.getView(position, convertView, parent); 

     PaymentType paymentType = getItem(position); 
     label.setText(paymentType.getStringResourceId()); 
     label.setCompoundDrawablesWithIntrinsicBounds(0, 0, paymentType. 
       getImageResourceId(), 0); 

     return label; 
    } 

    @Override 
    public View getDropDownView(int position, View convertView, ViewGroup parent) { 
     TextView label = (TextView) super.getDropDownView(position, convertView, parent); 

     PaymentType paymentType = getItem(position); 
     label.setText(paymentType.getStringResourceId()); 
     label.setCompoundDrawablesWithIntrinsicBounds(0, 0, paymentType. 
       getImageResourceId(), 0); 

     return label; 
    } 
} 

然後爲您的微調適配器:

mPaymentTypeArrayAdapter = new PaymentTypeArrayAdapter(getContext()); 
    setAdapter(mPaymentTypeArrayAdapter); 

在這種方法的關鍵是使用setCompoundDrawablesWithIntrinsicBounds的標籤要更改微調的背景