Android中的Android更改下拉样式/在所选项目上添加自己的图标

时间:2014-11-05 10:06:42

标签: android xml android-layout

我在Android / Xamarin项目中自定义微调器。它设置为SimpleSpinnerDropDownItem。我想添加带有所选/默认项目的图标。我已经用风格做的是Spinner背景(它是白色和圆形的),下拉列表中还有背景样式。

Spinner实现

Spinner spinner = FindViewById<Spinner>(Resource.Id.spinner);

spinner.ItemSelected += new EventHandler<AdapterView.ItemSelectedEventArgs>(spinner_ItemSelected);
var adapter = ArrayAdapter.CreateFromResource(
        this, Resource.Array.organisation_array, Android.Resource.Layout.SimpleSpinnerItem);

adapter.SetDropDownViewResource(Android.Resource.Layout.SimpleSpinnerDropDownItem);
spinner.SetSelection(1);
spinner.Adapter = adapter;

活动中的XML

<Spinner
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/spinner"
android:background="@drawable/rounded_shape"
style="@style/DropDownSpinner.My"
android:minHeight="50dp"
android:layout_marginTop="15dp"
android:layout_marginBottom="15dp"
android:layout_marginLeft="15dp"
android:layout_marginRight="15dp" />

XML样式

<style name="DropDownSpinner.My" parent="@android:style/Widget.Holo.Light.Spinner">
    <item name="android:popupBackground">@drawable/menu_dropdown_panel_spinner</item>
</style>

enter image description here

2 个答案:

答案 0 :(得分:0)

使用自定义布局创建自定义适配器。

public class MyAdapter extends ArrayAdapter<String>{

您应该为所选项目(包含文字和开始图标的布局)设置特殊布局

下面是 psudo代码

@Override
    public View getDropDownView(int position, View cnvtView, ViewGroup prnt){

        ...
        int selected = mySpinner.getSelectedItemPosition();

        if(position == selected){
            return special layout with the start icon
        }
        return normal layout

    }

答案 1 :(得分:0)

我希望此代码适合您:

private void spinner_ItemSelected (object sender, AdapterView.ItemSelectedEventArgs e)
{
    Spinner spinner = (Spinner)sender;

    spinner.GetItemAtPosition(e.Position)
                              .setCompoundDrawablesWithIntrinsicBounds(0, 0, R.drawable.favicone,0);
    // Reset the others 
}