jul*_*jul 0 variables android global adapter
我创建了一个扩展Application的类,在我的应用程序中包含全局变量.我用它们
((GlobalVars)getApplicationContext())
Run Code Online (Sandbox Code Playgroud)
但是当我尝试在我的自定义适配器中访问它时,这不会编译:
The method getApplicationContext() is undefined for the type FriendAdapter
Run Code Online (Sandbox Code Playgroud)
为什么?如何在适配器中访问我的全局变量?
谢谢
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);
}
}
Run Code Online (Sandbox Code Playgroud)
FriendAdapter
public class FriendAdapter extends ArrayAdapter<Friend> implements OnClickListener {
private ArrayList<Friend> items;
public FriendAdapter(Context context, int textViewResourceId,
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) {
...
}
}
Run Code Online (Sandbox Code Playgroud)
保持一个私有成员变量引用Adapter类中的上下文:
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;
}
Run Code Online (Sandbox Code Playgroud)
然后从上下文变量获取应用程序上下文的句柄:
if (((GlobalVars) mContext.getApplicationContext()).isFriendSelected(f.fb_id))
bCheck.setChecked(true);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
4085 次 |
| 最近记录: |