我們如何將微調器中的「選擇」(默認值)設置爲第一個值?我瀏覽過這裏,並沒有找到任何明確的解決方案或不理解它們。我在下面粘貼我的示例代碼。請根據我的理解提出解決方案或解釋。謝謝 !將微調器中的默認值設置爲「選擇」
這是我的MainActivity:
int[] icons = new int[]{R.drawable.bike, R.drawable.briefcase,
R.drawable.butterfly, R.drawable.coffee, R.drawable.home, R.drawable.kids, R.drawable.monitoring};
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_page2);
spinner = (Spinner) findViewById(R.id.spinner1);
CustomAdapter customAdapter = new CustomAdapter(this, getResources().getStringArray(R.array.titles),
getResources().getStringArray(R.array.description), icons);
spinner.setAdapter(customAdapter);
}
這是我的適配器低於
public class CustomAdapter extends ArrayAdapter<String>{
Context c;
String [] titles;
String [] desc;
int [] icons;
public CustomAdapter(Context context, String[] titles, String [] desc, int [] imgs) {
super(context, R.layout.layout_row, R.id.titles, titles);
this.c = context;
this.titles = titles;
this.desc = desc;
this.icons = imgs;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
View row = convertView;
MyViewHolder holder = null;
if(row == null){
LayoutInflater inflater = (LayoutInflater) c.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
row = inflater.inflate(R.layout.layout_row, parent, false);
holder = new MyViewHolder(row);
row.setTag(holder);
}else {
holder = (MyViewHolder) row.getTag();
}
holder.img_Icon.setImageResource(icons[position]);
holder.tv_Titles.setText(titles[position]);
holder.tv_Desc.setText(desc[position]);
return row;
}
}
class MyViewHolder{
TextView tv_Titles;
TextView tv_Desc;
ImageView img_Icon;
public MyViewHolder(View v) {
tv_Titles = (TextView) v.findViewById(R.id.titles);
tv_Desc= (TextView) v.findViewById(R.id.desc);
img_Icon = (ImageView) v.findViewById(R.id.icons);
}
}
我的字符串數組RES:
<string-array name="titles">
<item>Sunday</item>
<item>Monday</item>
<item>Tuesday</item>
<item>Wednesday</item>
<item>Thursday</item>
<item>Friday</item>
<item>Saturday</item>
</string-array>
<string-array name="description">
<item>This is Sunday</item>
<item>This is Monday</item>
<item>This is Tuesday</item>
<item>This is Wednesday</item>
<item>This is Thursday</item>
<item>This is Friday</item>
<item>This is Saturday</item>
</string-array>
添加「選擇」作爲數組中的第一個項目 –
謝謝,我早先想通了,但認爲可能有更好的方法?可以使用setSelection()方法以某種方式處理它嗎?如果是這樣,setSelection()如何處理? – user3755885
set selection()用於通過傳遞item的位置來設置默認的選定項目...以便您的項目應該位於列表中。 –