Android原生Spinner如何更改字体大小

自定义一个Spinner适配器

  • 这里有个奇怪的事情不知道怎么解释 我在spinner中tv.setTextSize(14f)的时候,设置的数值单位就是dp,比如我想设置字体是14dp 这里我如果通过工具类dp2px计算后传给TextView 就会不正确,反而是直接设置为14 就能得到想要的效果
public class MySpinnerAdapter extends ArrayAdapter<String> {

    private Context mContext;

    /**
     * spinner绑定的数组
     */
    private String[] mStringArray;

    /**
     *
     * @param context Context对象
     * @param stringArray spinner绑定的数组
     */
    public MySpinnerAdapter(Context context, String[] stringArray) {
        super(context, android.R.layout.simple_spinner_item, stringArray);
        mContext = context;
        mStringArray = stringArray;
    }
    //这里是Spinner展开后的文字修改
    @Override
    public View getDropDownView(int position, View convertView, ViewGroup parent) {
        if (convertView == null) {
            LayoutInflater inflater = LayoutInflater.from(mContext);
            convertView = inflater.inflate(android.R.layout.simple_spinner_dropdown_item, parent, false);
        }
        TextView tv = (TextView) convertView.findViewById(android.R.id.text1);
        tv.setText(mStringArray[position]);
        tv.setTextSize(14f);

        return convertView;

    }

    //这里是Spinner收起后的文字修改
    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        if (convertView == null) {
            LayoutInflater inflater = LayoutInflater.from(mContext);
            convertView = inflater.inflate(android.R.layout.simple_spinner_item, parent, false);
        }
        TextView tv = (TextView) convertView.findViewById(android.R.id.text1);
        tv.setText(mStringArray[position]);
        tv.setTextSize(14f);
        //tv.setTextColor(Color.BLUE);
        return convertView;
    }

}

在使用Spinner的时候需要重新给spinner设置自定义的适配器。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章