如何为Spinner的默认视图中显示的选项自定义/使用自定义布局?

时间:2015-03-04 18:16:31

标签: android spinner

在我写的应用程序中,我有一个整数列表,表示我用来制作Spinner的String资源ID。

我制作了一个自定义适配器并设置getDropDownView()来填充我的Spinner的下拉列表:

public View getDropDownView(int position, View convertView, ViewGroup parent) {
    int sortItem = getItem(position);
    ViewHolder viewHolder;
    if (convertView == null) {
        viewHolder = new ViewHolder();
        LayoutInflater inflater = LayoutInflater.from(getContext());
        convertView = inflater.inflate(R.layout.sort_item, parent, false);

        viewHolder.sortItemTv = (TextView) convertView.findViewById(R.id.sort_item_textview);

        convertView.setTag(viewHolder);
    } else {
        viewHolder = (ViewHolder) convertView.getTag();
    }

    viewHolder.sortItemTv.setText(convertView.getResources().getString(sortItem));
    return convertView;
}

这适用于下拉列表本身,但实际资源ID(整数)在下拉列表折叠时显示在Spinner中。我显然想要String,而不是资源ID。有没有办法使用自定义布局或显示来改变它?我是否需要制作自定义Spinner?

2 个答案:

答案 0 :(得分:0)

您还必须实施getView

getView -> collapsedView
getDropDownView -> expanded items

答案 1 :(得分:0)

想出来。我将该方法更改为getCustomView方法,并从getView和getDropDownView返回。

@Override
public View getView(int position, View convertView, ViewGroup parent) {
    return getCustomView(position, convertView, parent);
}

@Override
public View getDropDownView(int position, View convertView, ViewGroup parent) {
    return getCustomView(position, convertView, parent);
}

public View getCustomView(int position, View convertView, ViewGroup parent) {
    int sortItem = getItem(position);
    ViewHolder viewHolder;
    if (convertView == null) {
        viewHolder = new ViewHolder();
        LayoutInflater inflater = LayoutInflater.from(getContext());
        convertView = inflater.inflate(R.layout.sort_item, parent, false);

        viewHolder.sortItemTv = (TextView) convertView.findViewById(R.id.sort_item_textview);

        convertView.setTag(viewHolder);
    } else {
        viewHolder = (ViewHolder) convertView.getTag();
    }

    viewHolder.sortItemTv.setText(convertView.getResources().getString(sortItem));
    return convertView;
}