【问题标题】:Accessing adapter inside Fragment访问 Fragment 内的适配器
【发布时间】:2017-01-16 18:16:27
【问题描述】:

我有一个主 Activity.class,它通过 ViewPager 运行 Fragment (不是 FragmentActivity)。我在片段中有一个带有 recyclerview 列表的自定义适配器。访问 Fragment 外部和内部的适配器存在问题。所以:

此代码完全有效:

private List<MyQuestionList> theList;
private RecyclerView recyclerView;
private RecyclerView.Adapter adapter;

public View onCreateView(LayoutInflater inflater, ViewGroup container, 
Bundle savedInstanceState) {

    recyclerView = (RecyclerView) theview.findViewById(R.id.recyclerView);
    recyclerView.setHasFixedSize(true);

    theList = new ArrayList<>();
    requestQueue = Volley.newRequestQueue(getContext());

    adapter = new MyQuestionsAdapter(theList, getContext());

    recyclerView.setAdapter(adapter);

    updateAdapter();  // <-- ATTENTION PLEASE, I'VE CALLED THE FUNCTION INSIDE THE FRAGMENT

}

public void updateAdapter(){ // <-- METHOD IS PUBLIC
    removeItem(0);
}

***** And there is located parser's method where items are fetching from server
and adding to recyclerview via adapter successfully.
But the code is too long, and anyway there is nothing interesting :) *****

private void removeItem(int item){
    theList.remove(item);
    adapter.notifyDataSetChanged();
}

但是当我像这样从主 Activity.class 调用相同的方法(updateAdapter)时(不在运行时的片段内):

Fragment_Questions frau = new Fragment_Questions();
frau.updateAdapter();

代码不起作用。这是日志:

Caused by: java.lang.NullPointerException: Attempt to invoke interface method 'java.lang.Object java.util.List.remove(int)' on a null object reference

【问题讨论】:

  • 在哪里添加Fragment_QuestionsFragment?
  • 调用fragment的Activity.class里面。 public void openQuestion { adding Fragment_Questions }。 openQuestion 在 xml-layout 中被 onClick="openQuestion" 调用

标签: java android android-studio android-fragments


【解决方案1】:

既然您说Fragment_Questions 已经添加到ViewPager,请使用添加的Fragment_Questions 对象的引用来调用updateAdapter()。

在下面给出的代码中,您只是创建了一个对象,但从未将其添加到 viewpager。因此,永远不会调用 onCreateView 方法,这会导致 NullPointerException

【讨论】:

  • ViewPager 只是控制选项卡布局并在初始化时返回Fragment_Questions。那么如何实现该方案:用户单击布局的元素-> Activity.class inits 内部的方法X -> 方法X 调用Fragment_Questions 内部的方法?
  • 那么如何从activity中使用呢?
猜你喜欢
  • 2017-10-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-08-27
  • 2014-08-13
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多