我如何在Adapter类中使用我的全局变量? Android

问题描述 投票:-3回答:3

嗨,我正在尝试使用Global Variable传递值。我创建了一个类文件,并将其扩展为Application,然后将其添加到我的Manifest中。

public class MyApplication extends Application {}

[之后,我创建了一个扩展为Adapter ClassBaseExpandableListAdapter,我一直在研究如何设置和获取我创建并找到的全局变量

((MyApplication) getActivity().getApplication()).setMy_id(my_id);

并且为了获得我使用的值

Integer my_id = ((MyApplication) getActivity().getApplication()).getMy_id();

Fragments中,我可以使用getMy_id()方法,但是当将其放入BaseExpandableListAdapter中时,getActivity()中出现错误。我已经尝试过使用this,但仍然说Cannot resolve method getApplication(),还有其他方法可以获取我的全局变量的值。

我这样做是因为我想为我的Cursor使用ListView。我想创建一个Expandable ListView,其中的数据来自数据库,而我的Cursor有一个参数,用于WHERE条件,将使用我的全局变量中的数据。

之所以将它用作全局变量,是因为我在不同的Fragments中使用此数据,因为它不是静态的,它更改其值取决于所选项目。

谢谢你。

java android adapter expandablelistadapter
3个回答
1
投票

您需要在您的类中具有一个扩展BaseExpandableListAdapter的构造函数。定义的构造函数应接收Context类型的参数。这是示例-

private Context mContext;

public YourExpandableListAdapter(Context context) {
    mContext = context;
    Integer my_id = ((MyApplication) context.getApplicationContext()()).getMy_id();
}

现在在您的活动中创建这样的实例-

YourExpandableListAdapter ob = new YourExpandableListAdapter(this);

这应该起作用。


1
投票

我不确定您要达到的目标,但是无论您做什么,对我来说似乎都是很棘手!按照回答您的问题,getApplication()需要上下文,因此当您这样做时

((MyApplication) getActivity().getApplication())

您本质上是使用活动的(getActivity())上下文。并且您无法在getActivity()类中调用Adapter。尝试将活动的上下文从活动传递到构造函数中的适配器,类似。

MyAdapter myAdapter = new MyAdapter(this); //This line will be in your activity, and this will be the instance of your activity

并且您的适配器构造函数看起来像

public MyAdapter(Context context){
    //Use this context to get the application instance, something like
    Integer my_id = ((MyApplication) context.getApplication()).getMy_id();
}

0
投票

对我来说,以上所有方法均无效。试试这个:

((MyApplication) context.getApplicationContext()).getMy_id();
© www.soinside.com 2019 - 2024. All rights reserved.