如何在Android中的自定义适配器中使用我的全局变量?

时间:2011-03-03 11:45:09

标签: android variables global adapter

我创建了一个扩展Application的类,以便在我的应用中使用全局变量。我使用它们

((GlobalVars)getApplicationContext())

但是当我尝试在我的自定义适配器中访问它时,这不会编译:

The method getApplicationContext() is undefined for the type FriendAdapter

为什么呢?如何在适配器中访问我的全局变量?

由于


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,
            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) {
        ...
    } 

}

2 个答案:

答案 0 :(得分:7)

保持私有成员变量引用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;
}

然后从上下文变量中获取应用程序上下文的句柄:

if (((GlobalVars) mContext.getApplicationContext()).isFriendSelected(f.fb_id))
            bCheck.setChecked(true);

答案 1 :(得分:0)

ArrayAdapter不是上下文,因此您无法从此类获取Application。但是你可以在Activity中编写ArrayAdapter的实现(它是上下文)。当你初始化适配器时,这样的东西:

    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;
                }
            };