Android Spinner具有“下拉状态”和“关闭状态”的不同布局?

时间:2011-01-10 13:25:13

标签: android spinner android-spinner

我的布局中有一个Android Spinner视图。我希望该微调器在关闭时只显示一个文本项,但是当用户点击它时(即打开微调器对话框)我想为每个项显示更多信息,包括图标和其他描述文本视图。现在,微调器在两种状态下都显示相同的布局(图标,标题+描述)。

如果我将一个ArrayAdapter附加到微调器上,那么我可以访问一个名为“setDropDownViewResource”的东西,但这不一定是我需要的东西,因为我的微调器数据是从一个Cursor中取出而不是来自任何类型的数组(我有,截至目前,创建了我自己的适配器,扩展了BaseAdapter。)

任何可以帮助我的人?​​

6 个答案:

答案 0 :(得分:101)

您必须为Spinner创建一个自定义Adapter类,并为正常关闭视图覆盖两个方法getView(),并为下拉列表视图覆盖getDropDownView()。两种方法都必须为单个元素返回View个对象。

查看this tutorial它可能会帮助您入门。

答案 1 :(得分:13)

我也有问题。我没有重写这个课程,而是采用了一种更简单的方法来实现这一目标。

但首先,您需要了解适配器构造函数中的资源ID与setDropDownViewResource(...)中的另一个资源ID之间的区别。例如,

SimpleAdapter adapter =
    new SimpleAdapter(ab.getThemedContext(), data, R.layout.actionbar_dropdown, new String[] { "EventID", "Icon" },
        new int[] { R.id.event_id, R.id.icon });

adapter.setDropDownViewResource(R.layout.actionbar_list_item);

R.layout.actionbar_dropdown 微调器 的样式,每个列表项都是R.layout.actionbar_list_item

我在这里使用了SimpleAdapter,因为如果我使用ArrayAdapter,xml只能是一个TextView。

R.layout.actionbar_list_item包含一个ID为event_id的TextView和一个ID为icon的ImageView。

R.layout.actionbar_dropdownactionbar_list_item几乎完全相同,但后者的ImageView的可见性设置为 GONE

这样每个列表项都有一个textview和一个imageview,但你只会在微调器上看到一个textview。

答案 2 :(得分:10)

使用Flo链接的教程代码,我创建了以下CustomSpinnerAdapter,以显示两组不同的字符串,一组显示项目,一组不显示。我希望它有所帮助。

public class CustomSpinnerAdapter extends ArrayAdapter<String> {

Context mContext;
int mTextViewResourceId;
String[] mObjects;
String[] mShortNameObjects;

public CustomSpinnerAdapter(Context context, int textViewResourceId,
                            String[] objects, String[] shortNameObjects) {
    super(context, textViewResourceId, objects);
    mContext = context;
    mTextViewResourceId = textViewResourceId;
    mObjects = objects;
    mShortNameObjects = shortNameObjects;
}

@Override
public View getDropDownView(int position, View convertView,
                            ViewGroup parent) {
    LayoutInflater inflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);

    TextView row = (TextView) inflater.inflate(mTextViewResourceId, parent, false);
    row.setText(mObjects[position]);

    return row;
}

@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 = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);

    TextView row = (TextView) inflater.inflate(mTextViewResourceId, parent, false);
    row.setText(mShortNameObjects[position]);

    return row;
}
}

在片段中使用

CustomSpinnerAdapter mSpinnerAdapter = new CustomSpinnerAdapter(getActivity(), R.layout.spinner_item, getResources().getStringArray(R.array.action_filter), getResources().getStringArray(R.array.action_filter_short_names));

最后,微调项目的布局:

spinner_item.xml

<?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:textSize="18dip"
    android:gravity="left"
    android:textColor="@color/navdraw_list_item_background_default"
    android:padding="5dip" />

答案 3 :(得分:8)

仅使用替代布局设置下拉视图资源:

ArrayAdapter<String> genderAdapter = new ArrayAdapter<>(this, R.layout.adapter_spinner_white, Constants.GENDER);
genderAdapter.setDropDownViewResource(R.layout.adapter_spinner_white_dropdown);
view.setAdapter(genderAdapter);

对我来说,它只是一个带有额外填充的布局,因为我的微调器的背景是圆形的可绘制的,需要这个额外的空间。

答案 4 :(得分:1)

在获取对Spinner的引用后只需调用setUpSpinner()方法

//这是setUpSpinner方法

private void setupSpinner() {

    // Create adapter for spinner. The list options are from the String array it will use
    // the spinner will use the default layout
    ArrayAdapter spinnerAdapter = ArrayAdapter.createFromResource(this,
            R.array.array_dropdown_options, android.R.layout.simple_spinner_item);

    // Specify dropdown layout style - simple list view with 1 item per line
    spinnerAdapter.setDropDownViewResource(android.R.layout.simple_dropdown_item_1line);

    // Apply the adapter to the spinner
    spinner.setAdapter(spinnerAdapter);
   // spinner is referenced spinner by finViewById.

    spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
        @Override
        public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
            String selection = (String) parent.getItemAtPosition(position);
            if (!TextUtils.isEmpty(selection)) {
                if (selection.equals(getString(R.string.item_a))) {
                    // your code for selected item whose id equals to id to R.string.item_a
                } else if (selection.equals(getString(R.string.item_b))) {
                    // your code
                } else {
                    // your code
                }
            }
        }

        // Because AdapterView is an abstract class, onNothingSelected must be defined
        @Override
        public void onNothingSelected(AdapterView<?> parent) {
            // code for nothing selected in dropdown
        }
    });
}

答案 5 :(得分:0)

我对ArrayAdapter进行了扩展,它尽可能地保留了其功能,只是对所选项目设置了详细说明。

首先,我们需要一种用于馈送适配器的新模型。请注意,toString()返回shortDescription,以便ArrayAdapter在下拉列表中显示简短说明:

data class DescriptiveArrayItem(val shortDescription: String, val longDescription: String) {
    override fun toString(): String {
        return shortDescription
    }
}

第二,我们创建我们的自定义适配器,该适配器将覆盖getView()并显示选中该项目时的详细说明(不幸的是,ArrayAdapter中的许多字段和方法都是私有的,因此我不得不复制它们):

class DescriptiveArrayAdapter : ArrayAdapter<DescriptiveArrayItem> {
    private var mResource: Int
    private val mFieldId: Int
    private val mContext: Context
    private val mInflater: LayoutInflater

    constructor(context: Context, resource: Int) : super(context, resource) {
        mContext = context
        mFieldId = 0
        mInflater = LayoutInflater.from(context)
        mResource = resource
    }
    constructor(context: Context, resource: Int, textViewResourceId: Int) : super(context, resource, textViewResourceId) {
        mContext = context
        mFieldId = textViewResourceId
        mInflater = LayoutInflater.from(context)
        mResource = resource
    }
    constructor(context: Context, resource: Int, objects: Array<out DescriptiveArrayItem>) : super(context, resource, objects) {
        mContext = context
        mFieldId = 0
        mInflater = LayoutInflater.from(context)
        mResource = resource
    }
    constructor(context: Context, resource: Int, textViewResourceId: Int, objects: Array<out DescriptiveArrayItem>) : super(context, resource, textViewResourceId, objects) {
        mContext = context
        mFieldId = textViewResourceId
        mInflater = LayoutInflater.from(context)
        mResource = resource
    }
    constructor(context: Context, resource: Int, objects: List<DescriptiveArrayItem>) : super(context, resource, objects) {
        mContext = context
        mFieldId = 0
        mInflater = LayoutInflater.from(context)
        mResource = resource
    }
    constructor(context: Context, resource: Int, textViewResourceId: Int, objects: List<DescriptiveArrayItem>) : super(context, resource, textViewResourceId, objects) {
        mContext = context
        mFieldId = textViewResourceId
        mInflater = LayoutInflater.from(context)
        mResource = resource
    }

    override fun getView(position: Int, convertView: View?, parent: ViewGroup): View {
        return createViewFromResource(mInflater, position, convertView, parent, mResource)
    }

    private fun createViewFromResource(inflater: LayoutInflater, position: Int,
                                       convertView: View?, parent: ViewGroup, resource: Int): View {
        val text: TextView?
        val view: View = convertView ?: inflater.inflate(resource, parent, false)
        try {
            if (mFieldId == 0) {
                //  If no custom field is assigned, assume the whole resource is a TextView
                text = view as TextView
            } else {
                //  Otherwise, find the TextView field within the layout
                text = view.findViewById(mFieldId)
                if (text == null) {
                    throw RuntimeException("Failed to find view with ID "
                            + mContext.resources.getResourceName(mFieldId)
                            + " in item layout")
                }
            }
        } catch (e: ClassCastException) {
            Log.e("ArrayAdapter", "You must supply a resource ID for a TextView")
            throw IllegalStateException(
                    "ArrayAdapter requires the resource ID to be a TextView", e)
        }
        val item: DescriptiveArrayItem? = getItem(position)
        text.text = item?.longDescription
        return view
    }
}