Sunday, January 13, 2019

Dùng custom adapter cho nhiều Spinner android

Đôi khi ta cần dùng custom adapter cho nhiều listview hoặc spinner khác nhau. Lúc đó, không cần phải tạo một custom adapter khác mà ta có thể thêm biến để tuỳ chỉnh trong một adaper.
Giả sử ta muốn set spinner thứ nhất chữ có màu đỏ, cái thứ hai màu xanh, ta chỉ cần dùng một class custom adapter như sau.
public class CustomListAdapter extends ArrayAdapter<String> {
          private final Activity context;
          int so;
          private final String[]  item;
     public CustomListAdapter(Activity context, String[] item,int so) {
               super(context, R.layout.lim, item);
               // TODO Auto-generated constructor stub
               so=so;
               this.context=context;
               this.item=item;
          }
          @SuppressLint({ "ViewHolder", "InflateParams" })
public View getView(int position,View view,ViewGroup parent) {
LayoutInflater inflater=context.getLayoutInflater();
View rowView=inflater.inflate(R.layout.lim, null,true);
              
TextView txt = (TextView) rowView.findViewById(R.id.tem);
               txt.setText(item[position]);
txt.setTextSize(android.util.TypedValue.COMPLEX_UNIT_DIP, 15);
if(so==1){
     txt.setTextColor(Color.RED);
     }
if(so==2){
     txt.setTextColor(Color.BlUE);
     }
if(so==3){
txt.setTextColor(Color.GREEN);
txt.setTextSize(android.util.TypedValue.COMPLEX_UNIT_DIP, 20);
     }
return rowView;
};
}
File lim.xml ở trong folder layout như sau.
<?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/tem"
    android:layout_width="match_parent"
    android:layout_height="45sp"
    android:gravity="center"
    android:textColor="#0000cd"
  android:textSize="15sp" />
Khi dùng, ta set như sau nếu muốn chữ màu đỏ.
private Spinner spin;
private ArrayAdapter<String> adapter;
adapter=new CustomListAdapter(this,data,1);
spin.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> parent, View view,int position, long id) {             
String chon=spin.getSelectedItem().toString();
}
@Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
});
spin.setAdapter(adapter);
spin.setSelection(4);
data là mảng dữ liệu của spin. Thay số 1 thành 2, 3 trong lệnh adapter=new CustomListAdapter(this,data,1);nếu muốn màu xanh. Nếu dùng số 3 chữ sẽ có màu xanh lá và cỡ 20 cố định trên mọi điện thoại bất kể độ phân giải hoặc người dùng để setting chữ cỡ nào.
Để có nhiều màu hơn, chỗ Color có thể dùng.

Color.parseColor("#8C001A")

No comments:

Post a Comment