[英]How to get variable on activity from BaseAdapter Android
Im having a variable, bill_id
on MainActivity.
我在
MainActivity.
上有一个变量bill_id
MainActivity.
Then on MainActivity
, I also has list view
category, i put onItemClick
on CategoryListAdapter.
然后在
MainActivity
,我也有list view
类别,我把onItemClick
放在CategoryListAdapter.
Here, when i click the category i want to reload the activity, which is new intent
, and also pass variables, i want to pass category_id
and bill_id
(which is from MainActivity
) 在这里,当我点击我要重新加载活动的类别,这是
new intent
,并且还传递变量时,我想传递category_id
和bill_id
(来自MainActivity
)
how can i get bill_id
value from BaseAdapter
? 如何从
BaseAdapter
获取bill_id
值?
here my snippet: 这里是我的片段:
final int category_id = listData.get(position).getID();
final String category_name = listData.get(position).get_name();
holder.btnCategory.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v){
Log.d(TAG, "click category:"+category_id);
Log.d(TAG, "category selected:"+category_name);
// get cat id, reload with its id
db = new DatabaseHelper(aContext);
// bring variable id, to POS interface
Intent intent = new Intent(aContext, MainActivity.class);
intent.putExtra("category_id", category_id);
v.getContext().startActivity(intent);
}
});
It is simple. 很简单。 Pass the values from your Activity to the Adapter using the adapter's constructor.
使用适配器的构造函数将值从Activity传递到适配器。 This is what the constructors are for.
这就是构造函数的用途。
Like in your activity, 就像你的活动一样
MyAdapter myAdapter = new MyAdapter(variable1, variable2);
Now in your adapter, 现在在你的适配器中,
private int variable1, variable2;
// Constructor
public MyAdapter(int var1, int var2){
this.variable1 = var1;
this.variable2 = var2;
}
You can now easily use these variables in your click listener and pass them to the new intent. 您现在可以在点击侦听器中轻松使用这些变量,并将它们传递给新意图。
You can also use setters for these variables in the adapter like, 你也可以在适配器中使用这些变量的setter,比如
public void setVariable1(int value){
this.variable1 = value;
}
public void setVariable2(int value){
this.variable2 = value;
}
And from your activity, do something like this whenever needed, 根据您的活动,在需要时做这样的事情,
myAdapter.setVariable1(10);
So, these are the ways for you to access your variables from your activity inside your adapter. 因此,这些是您从适配器内的活动访问变量的方法。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.