要自定义Spinner Adapter的样式,您需要创建一个自定义适配器并覆盖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));
// 在这里设置其他样式,例如字体颜色、大小等
return convertView;
}
@Override
public View getDropDownView(int position, View convertView, ViewGroup parent) {
// 使用相同的布局和视图持有者来设置下拉列表项的样式
return getView(position, convertView, parent);
}
static class ViewHolder {
TextView textView;
}
}
Spinner spinner = findViewById(R.id.spinner);
List<String> data = new ArrayList<>();
// 添加数据到列表中
CustomSpinnerAdapter adapter = new CustomSpinnerAdapter(this, R.layout.list_item, data);
spinner.setAdapter(adapter);
现在,您的Spinner应该具有自定义的样式。根据需要调整list_item.xml
布局以及CustomSpinnerAdapter
中的样式设置。