如何改變spinner控件的字體大小

小樊
263
2024-07-10 10:05:26
欄目: 編程語言

要改變Spinner控件的字體大小,可以通過自定義Spinner的樣式和設(shè)置Adapter來實(shí)現(xiàn)。

  1. 創(chuàng)建一個(gè)自定義的Spinner樣式(styles.xml):
<style name="SpinnerStyle" parent="Widget.AppCompat.Spinner">
    <item name="android:textSize">16sp</item> <!-- 設(shè)置字體大小 -->
</style>
  1. 在布局文件中使用自定義的Spinner樣式:
<Spinner
    android:id="@+id/spinner"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:theme="@style/SpinnerStyle" />
  1. 創(chuàng)建一個(gè)自定義的Adapter并設(shè)置字體大?。–ustomAdapter.java):
public class CustomAdapter extends ArrayAdapter<String> {
    private Context mContext;
    private int mResource;
    private List<String> mData;
    private LayoutInflater mInflater;

    public CustomAdapter(Context context, int resource, List<String> data) {
        super(context, resource, data);
        this.mContext = context;
        this.mResource = resource;
        this.mData = data;
        this.mInflater = LayoutInflater.from(context);
    }

    @NonNull
    @Override
    public View getView(int position, @Nullable View convertView, @NonNull ViewGroup parent) {
        if (convertView == null) {
            convertView = mInflater.inflate(mResource, parent, false);
        }

        TextView textView = convertView.findViewById(android.R.id.text1);
        textView.setText(mData.get(position));
        textView.setTextSize(16); // 設(shè)置字體大小

        return convertView;
    }

    @Override
    public View getDropDownView(int position, @Nullable View convertView, @NonNull ViewGroup parent) {
        if (convertView == null) {
            convertView = mInflater.inflate(mResource, parent, false);
        }

        TextView textView = convertView.findViewById(android.R.id.text1);
        textView.setText(mData.get(position));
        textView.setTextSize(16); // 設(shè)置字體大小

        return convertView;
    }
}
  1. 在Activity中設(shè)置Spinner的Adapter:
Spinner spinner = findViewById(R.id.spinner);
List<String> data = new ArrayList<>();
data.add("Option 1");
data.add("Option 2");
data.add("Option 3");

CustomAdapter adapter = new CustomAdapter(this, android.R.layout.simple_spinner_item, data);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(adapter);

通過以上步驟,就可以改變Spinner控件的字體大小。

0