Sometime we need custom adapter for many spinners. No
need to create many custom adapter, we can add variable to custom adapter.
For example, we want to set first spinner with red color text,
second blue, we use one class custom adapter like this.
public class CustomListAdapter extends ArrayAdapter<String> {
private final Activity context;
int number;
private final String[] item;
public CustomListAdapter(Activity context,
String[] item,int number) {
super(context, R.layout.lim, item);
// TODO Auto-generated constructor stub
number=number;
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(number==1){
txt.setTextColor(Color.RED);
}
if(number==2){
txt.setTextColor(Color.BlUE);
}
if(number==3){
txt.setTextColor(Color.GREEN);
txt.setTextSize(android.util.TypedValue.COMPLEX_UNIT_DIP, 20);
}
return rowView;
};
}
File lim.xml in folder layout like this.
<?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"
/>
When using, to make text color red, we do like this.
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 choose=spin.getSelectedItem().toString();
}
@Override
public void
onNothingSelected(AdapterView<?> arg0)
{
// TODO Auto-generated method stub
}
});
spin.setAdapter(adapter);
spin.setSelection(4);
data is the data array use for spinner. Change number 1 to 2 if want
text blue. If use 3, text color green and has 20pt size fix for all screen
resolution and setting.
To have many colors choice, the line Color.RED can change to.
Color.parseColor("#8C001A")
This custom spinner adapter example
can be use for listview too.
No comments:
Post a Comment