我正在开发一个与Android应用程序相关的项目,在该项目中,我使用了两个下拉菜单。我从网络服务中获取了数据,并将其存储在两个列表数组中,然后将这两个列表数组分别分配给下拉菜单。但是,在分配列表数组之前,我必须为下拉菜单分配一些默认值,例如“选择类别”和“选择子类别”。那么如何实现呢?请帮助我。
提前感谢您的帮助。
提前感谢您的帮助。
使用 ArrayList 替代 array。在从 Web 服务添加值之前,首先向列表中添加默认值。
您可以按照以下方式使用。
ArraList<String> list=new ArrayList<String>();
list.add("Select Category");
//Your logic to get data from web services
//Add the data to array list.
list.add("data1");
list.add("data2");
String defaultTextForSpinner = "Select Category";
Spinner spinnerCategory = (Spinner)
.findViewById(R.id.spinner2);
接下来,您需要为 spinner
制作 自定义适配器
CategoryAdapter cat_adapter = new CategoryAdapter(this, categoryList,
R.layout.spinner_row, defaultTextForSpinner);
spinnerCategory.setAdapter(cat_adapter);
cat_adapter.notifyDataSetChanged();
适配器类:
public class CategoryAdapter extends ArrayAdapter<String> {
Activity context;
ArrayList<HashMap<String, String>> categoryList;
String firstElement;
boolean isFirstTime;
LayoutInflater mInflater;
String[] objects;
public CategoryAdapter(FragmentActivity context,
ArrayList<HashMap<String, String>> categoryList, int spinnerRow,
String defaultTextForSpinner) {
super(context, spinnerRow);
this.context = context;
this.categoryList = categoryList;
this.constant = new Const(context);
mInflater = LayoutInflater.from(context);
objects = new String[this.categoryList.size()];
setDefaultText(defaultTextForSpinner);
}
@Override
public View getDropDownView(int position, View convertView, ViewGroup parent) {
for (int i = 0; i < categoryList.size(); i++) {
objects[i] = categoryList.get(i).get("category_name");
}
if (isFirstTime) {
objects[0] = firstElement;
isFirstTime = false;
}
return getCustomView(position, convertView, parent);
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
notifyDataSetChanged();
return getCustomView(position, convertView, parent);
}
public void setDefaultText(String defaultText) {
this.firstElement = objects[0];
objects[0] = defaultText;
}
public View getCustomView(int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View row = inflater.inflate(R.layout.spinner_row, parent, false);
TextView label = (TextView) row.findViewById(R.id.txtSpinner);
label.setText(objects[position]);
return row;
}
@Override
public int getCount() { // TODO Auto-generated method stub
return objects.length;
}
}