【问题标题】:getting context of fragment in baseadapter在 baseadapter 中获取片段的上下文
【发布时间】:2014-06-15 01:55:03
【问题描述】:

这对我来说变得很复杂,因为我对片段不太熟悉,但对你们中的一些人来说也可能很简单,这里我有这部分代码引用一个活动,当我将活动更改为片段时上面写着can not cast from context to ListViewActivity,你能帮我解决这个问题吗:

 @Override
public Filter getFilter() {
    return ((ListViewActivity)mContext).new ListFilter();
}

显然mContext 是上下文引用。我知道片段内部应该使用getActivity() 获取上下文,但从外部获取上下文?非常感谢。

【问题讨论】:

  • 发布 ListViewActivity

标签: android


【解决方案1】:

我会构建一个类似这样的自定义适配器:

public class CustomBaseAdapter extends BaseAdapter {
Context context;
List<RowItem> rowItems;

public CustomBaseAdapter(Fragment fragment, List<RowItem> items) {
    this.context = fragment.getActivity();
    this.rowItems = items;
}
}

在你的片段中,像这样调用适配器:

CustomBaseAdapter adapter = new CustomBaseAdapter(this, items);

现在您可以将适配器中的上下文转换为 ListViewActivity,假设片段是 ListViewActivity 的一部分。

希望这会有所帮助!

【讨论】:

  • 我放在那里的过滤器是用来搜索的,所以我需要在适配器中获取上下文
  • 是的,上下文只是基础对象。因此,每个 Activity(以及应用程序)都源自 Context。欲了解更多信息,请阅读:stackoverflow.com/questions/6518206/…
猜你喜欢
  • 2013-05-11
  • 2016-08-19
  • 1970-01-01
  • 1970-01-01
  • 2015-05-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多