How can I use my global vars in a custom adapter in Android?
I created a class extending Application to have global variables in my app. I use them using
((GlobalVars)getApplicationContext())
but this does not compile when I'm trying to access it in my custom adapter:
The method getApplicationContext() is undefined for the type FriendAdapter
Why? How can I access my global vars in my adapter?
Thanks
GlobalVars
public class GlobalVars extends Application {
private ArrayList<String> selectFriendList = new ArrayList<String>();
public void addSelectedFriend(String fb_id) {
this.selectFriendList.add(fb_id);
}
public void removeSelectedFriend(String fb_id) {
this.selectFriendList.remove(fb_id);
}
public boolean isFriendSelected(String fb_id) {
return this.selectFriendList.contains(fb_id);
}
}
FriendAdapter
public class FriendAdapter extends ArrayAdapter<Friend> implements OnClickListener {
private ArrayList<Friend> items;
public FriendAdapter(Context context, int textViewResourceId,开发者_如何学Python
ArrayList<Friend> items) {
super(context, textViewResourceId, items);
this.items = items;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
View v = convertView;
if (v == null) {
LayoutInflater vi = (LayoutInflater) getContext().getSystemService(
Context.LAYOUT_INFLATER_SERVICE);
v = vi.inflate(R.layout.contact_row, null);
}
Friend f = items.get(position);
if (f != null) {
String name = f.name;
TextView tt = (TextView) v.findViewById(R.id.contact_name);
tt.setText(name);
CheckBox bCheck = (CheckBox) v.findViewById(R.id.checkbox);
bCheck.setTag(f.fb_id);
if (((GlobalVars)getApplicationContext()).isFriendSelected(f.fb_id))
bCheck.setChecked(true);
bCheck.setOnClickListener(this);
}
return v;
}
@Override
public void onClick(View v) {
...
}
}
Keep a private member variable referencing the context within your Adapter class:
private Context mContext;
private ArrayList<Friend> items;
public FriendAdapter(Context context, int textViewResourceId,
ArrayList<Friend> items) {
super(context, textViewResourceId, items);
this.items = items;
this.mContext = context;
}
Then get a handle to your application context from the context variable:
if (((GlobalVars) mContext.getApplicationContext()).isFriendSelected(f.fb_id))
bCheck.setChecked(true);
ArrayAdapter isn't a context, so you can't get Application from this class. But you can write ArrayAdapter's implementation in Activity(it is context). Something like this, when you initialize adapter:
ArrayAdapter<String> A = new ArrayAdapter<String>(this, R.layout.item_view,
new String[]{"1", "2"}){
@Override
public View getView(int position, View convertView, ViewGroup parent) {
//get view implementation
return convertView;
}
};
精彩评论