Android 如何从适配器访问 ListView
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10910638/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How do I access to ListView from the adapter
提问by user1049280
I have a custom ListView
with my own adapter. I'm handling the click on a Button
in my ListView
's item, and I want the ListView
to become invisible on this click.
我对ListView
自己的适配器有一个自定义。我正在处理对Button
我 ListView
的项目中的a 的点击,并且我希望ListView
在这次点击中变得不可见。
I have no idea how to get access to the ListView
from the adapter.
我不知道如何ListView
从适配器访问。
public class ScheduleArrayAdapter extends ArrayAdapter<ScheduleListItem> {
/*...*/
@Override
public View getView(int position, View convertView, ViewGroup parent) {
View v = convertView;
if (v == null) {
LayoutInflater vi = (LayoutInflater)c.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
v = vi.inflate(id, null);
}
final ScheduleListItem o = items.get(position);
if (o != null) {
/*...*/
Button details=(Button)v.findViewById(R.id.btn_details);
details.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//HOW TO MAKE (R.id.lv_schedule) TO BECOME INVISIBLE HERE?
}
});
}
return v;
}
}
回答by Vladimir
ViewGroup parent
holds reference to the parent of the View
returned by getView()
, which in your case is your custom listview.
ViewGroup parent
持有对View
返回的父级的引用by getView()
,在您的情况下是您的自定义列表视图。
@Override
public View getView(int position, View convertView, final ViewGroup parent) {
...
details.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
parent.setVisibility(View.INVISIBLE); // or View.GONE
}
});
...
return v;
}
回答by Pramod
Instead of this you can pass the reference of your Listview through constructor of adapter and store that in local Listview variable. You can use this for access your Listviews method.Like this
取而代之的是,您可以通过适配器的构造函数传递 Listview 的引用,并将其存储在本地 Listview 变量中。您可以使用它来访问您的 Listviews 方法。像这样
public ViewPackagesAdapter(Activity mActivity, ListView cmgListView) {
this.mActivity = mActivity;
this.mListView=cmgListView;
}
Now access Activity's Listview through mListView..
现在通过 mListView 访问 Activity 的 Listview ..
回答by anand krish
In my case GridItemClickListner didn't worked for some reason. I access the Gridview from Adapter classusing this
在我的情况下 GridItemClickListner 由于某种原因没有工作。我使用这个从 Adapter 类访问Gridview
public View getView(final int position, View convertView, ViewGroup parent) {
convertView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
((ClockGridView) v.getParent()).performItemClick(v, position, v.getId());
(OR)
((ClockGridView)parent).performItemClick(v, position, v.getId());
}
});
}
"ClockGridView" which extends "GridView" Class.
扩展“GridView”类的“ClockGridView”。