要自定義Spinner Adapter的樣式,您需要?jiǎng)?chuàng)建一個(gè)自定義適配器并覆蓋getView()
和getDropDownView()
方法
<?xml version="1.0" encoding="utf-8"?><TextView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/text_view"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="8dp"
android:textSize="16sp"
android:textColor="@color/your_text_color" />
ArrayAdapter
或BaseAdapter
。import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;
import java.util.List;
public class CustomSpinnerAdapter extends ArrayAdapter<String> {
private List<String> data;
private LayoutInflater inflater;
public CustomSpinnerAdapter(Context context, int resource, List<String> objects) {
super(context, resource, objects);
this.data = objects;
inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
if (convertView == null) {
convertView = inflater.inflate(R.layout.list_item, parent, false);
holder = new ViewHolder();
holder.textView = convertView.findViewById(R.id.text_view);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
holder.textView.setText(data.get(position));
// 在這里設(shè)置其他樣式,例如字體顏色、大小等
return convertView;
}
@Override
public View getDropDownView(int position, View convertView, ViewGroup parent) {
// 使用相同的布局和視圖持有者來(lái)設(shè)置下拉列表項(xiàng)的樣式
return getView(position, convertView, parent);
}
static class ViewHolder {
TextView textView;
}
}
Spinner spinner = findViewById(R.id.spinner);
List<String> data = new ArrayList<>();
// 添加數(shù)據(jù)到列表中
CustomSpinnerAdapter adapter = new CustomSpinnerAdapter(this, R.layout.list_item, data);
spinner.setAdapter(adapter);
現(xiàn)在,您的Spinner應(yīng)該具有自定義的樣式。根據(jù)需要調(diào)整list_item.xml
布局以及CustomSpinnerAdapter
中的樣式設(shè)置。