要自定義Android Spinner的樣式,可以通過以下步驟實現:
<?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/spinner_item"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="10dp"
android:textSize="16sp"
android:textColor="@color/black"/>
public class CustomSpinnerAdapter extends ArrayAdapter<String> {
private Context mContext;
private List<String> mData;
public CustomSpinnerAdapter(Context context, List<String> data) {
super(context, R.layout.custom_spinner_item, data);
mContext = context;
mData = data;
}
@NonNull
@Override
public View getView(int position, @Nullable View convertView, @NonNull ViewGroup parent) {
View view = convertView;
if (view == null) {
view = LayoutInflater.from(mContext).inflate(R.layout.custom_spinner_item, parent, false);
}
TextView textView = view.findViewById(R.id.spinner_item);
textView.setText(mData.get(position));
return view;
}
@Override
public View getDropDownView(int position, @Nullable View convertView, @NonNull ViewGroup parent) {
return getView(position, convertView, parent);
}
}
List<String> data = new ArrayList<>();
data.add("Option 1");
data.add("Option 2");
data.add("Option 3");
Spinner spinner = findViewById(R.id.spinner);
CustomSpinnerAdapter adapter = new CustomSpinnerAdapter(this, data);
spinner.setAdapter(adapter);
通過以上步驟,可以自定義Android Spinner的樣式,并實現自定義的樣式效果。