查看扩展BaseAdapter的自定义适配器:
public class DrawerAdapter extends BaseAdapter{
static class ViewHolder{
TextView cat_Title;
TextView cat_Count;
}
private Activity mActivity;
private ArrayList<HashMap<String, String>> mData;
private static LayoutInflater mInflater;
private JsonArray Categories = null;
public JsonObject Cat_Items = null;
private static String CATEGORY_NAME;
private static String CATEGORY_CNT;
private static String CATEGORY_ID;
public DrawerAdapter(Activity a, ArrayList<HashMap<String, String>> d){
mActivity = a;
mData = d;
mInflater = (LayoutInflater) mActivity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
@Override
public int getCount() {
return mData.size();
}
@Override
public Object getItem(int position) {
return position;
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
View dView = convertView;
ViewHolder holder = null;
HashMap<String, String> dCategorise = new HashMap<String, String>();
dCategorise = mData.get(position);
CATEGORY_NAME = dCategorise.get("CATEGORY_NAME");
CATEGORY_CNT = dCategorise.get("CATEGORY_CNT");
CATEGORY_ID = dCategorise.get("CATEGORY_ID");
if (convertView == null){
dView = mInflater.inflate(R.layout.layout_drawer_list_row, null);
holder = new ViewHolder();
holder.cat_Title = (TextView) dView.findViewById(R.id.category_title);
holder.cat_Count = (TextView) dView.findViewById(R.id.category_counter);
dView.setTag(holder);
}else{
holder = (ViewHolder) dView.getTag();
}
holder.cat_Title.setTag(position);
holder.cat_Title.setTypeface(MyriadRegular);
holder.cat_Title.setText(CATEGORY_NAME);
holder.cat_Count.setTypeface(Yagut);
holder.cat_Count.setText(CATEGORY_CNT);
holder.cat_Title.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
int pos = (Integer) v.getTag();
String cat_ID = mData.get(pos).get(CATEGORY_ID);
}
});
return dView;
}
}
这是我的自定义适配器,我正在导航抽屉中使用它。我想通过点击category title来获取category id,并将其发送到片段,然后在此基础上更改片段数据。
但是猫的id返回空值
现在我的问题是:
1.为什么返回空值?
2.获取发送到片段的类别ID的方法正确吗?
最佳答案
我建议在您从hashmap中获得按钮标记时直接将CATEGORY_ID
添加到按钮标记中
样品:
改变这一点:
holder.cat_Title.setTag(position);
到:
holder.cat_Title.setTag(CATEGORY_ID);
public void onClick(View v) {
String cat_ID = (String) v.getTag();
}