如何将适配器调到Fragment?

时间:2015-09-17 17:51:55

标签: android android-fragments android-activity adapter

我使用3个标签,每个标签都有片段。我需要将此活动带到片段的片段。这有可能吗?

public class MActivity extends Activity {

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.grid_layout);
    GridView gridView = (GridView) findViewById(R.id.grid_view);
    gridView.setAdapter(new ImageAdapter(this));
}

}

public class FragmentTab1 extends Fragment {

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

    View rootView = inflater.inflate(R.layout.grid_layout, container, false);
    GridView gridView = (GridView) getActivity().findViewById(R.id.grid_view);


    return rootView;
}

有人可以帮我编辑片段类以从Adapter获取活动。 感谢

3 个答案:

答案 0 :(得分:1)

here.

得到了正确答案
    public View onCreateView (LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    View view = inflater.inflate(R.layout.tab_1,container,false);
    GridView gridView = (GridView) view.findViewById(R.id.grid_view);
    gridView.setAdapter(new ImageAdapter(view.getContext()));
    return view;
}

答案 1 :(得分:0)

一个不太干净,但最简单的方法是这样做:

n%4 == 0

在您的活动中公开适配器getter>

 public class FragmentTab1 extends Fragment {

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

        View rootView = inflater.inflate(R.layout.tab_1, container, false);
        activityAdapter = (MActivity)getActivity().getImageAdapter();
        return rootView;
    }

第二种方法是在片段中创建构造函数,以在构造片段时接收适配器对象。 (这将是一个更清洁的对象)

答案 2 :(得分:0)

如果我对您的问题的理解是正确的,一种方法是通过ViewPager适配器和片段的构造函数传递活动/上下文对象。