无法从recyclerview打开片段

时间:2015-12-08 07:43:41

标签: android navigation-drawer android-recyclerview

我使用navigation bar创建了包含一些内容的recyclerview,我添加了fragments这些内容,但fragments没有打开。

该应用为crashing尝试向recyclerview调用虚拟方法。

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.GestureDetector;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;

import com.sun.suni.design.fragments.AboutUS;
import com.sun.suni.design.fragments.Overview;
import com.sun.suni.design.fragments.Products;
import com.sun.suni.design.fragments.ReachUs;

import java.util.ArrayList;
import java.util.List;


/**
 * A simple {@link Fragment} subclass.
 */
public class NavigationDrawerFragment extends Fragment {

    private RecyclerView recyclerView;
    private ActionBarDrawerToggle sDrawerToggle;
    private DrawerLayout sDrawerLayout;
    private SunAdapter adapter;
    private View containerView;
    public static final String PREF_FILE_NAME = "navtest";
    public static final String KEY_USER_LEARNED_DRAWER = "user_learned_drawer";
    private boolean sUserLearnedDrawer;
    private boolean sFromSavedInstanceState;
    public NavigationDrawerFragment() {
        // Required empty public constructor
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        sUserLearnedDrawer = Boolean.valueOf(readFromPreferences(getActivity(),KEY_USER_LEARNED_DRAWER,"false"));
        if (savedInstanceState != null) {
            sFromSavedInstanceState = true;
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View layout =  inflater.inflate(R.layout.fragment_navigation_drawer, container, false);
        recyclerView = (RecyclerView) layout.findViewById(R.id.drawer_list);
        adapter = new SunAdapter(getActivity(),getData());
        recyclerView.setAdapter(adapter);
        recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
        recyclerView.addOnItemTouchListener(new RecyclerTouchListener(getActivity(), recyclerView, new ClickListener() {
            @Override
            public void onClick(View view, int posititon) {
                    Fragment fragment = null;
                    switch (posititon) {
                        case 0:
                            fragment = new Products();
                            break;
                        case 1:
                            fragment = new AboutUS();
                            break;
                        case 2:
                            fragment = new Overview();
                            break;
                        case 3:
                            fragment = new ReachUs();
                            break;
                        default:
                            break;
                    }

                    if (fragment != null) {
                        FragmentManager fragmentManager = getFragmentManager();
                        fragmentManager.beginTransaction()
                                .replace(R.id.drawer_list, fragment).commit();

                        // update selected item and title, then close the drawer
                    } else {
                        // error in creating fragment
                        Log.e("MainActivity", "Error in creating fragment");
                    }
                }

            @Override
            public void onLongClick(View view, int position) {
                Toast.makeText(getActivity(),"onLongClick"+position,Toast.LENGTH_SHORT).show();
            }

        }));
        return layout;
    }


    public static List<Info> getData(){
        List<Info> data = new ArrayList<>();
        int[] icons = {R.drawable.products,R.drawable.aboutus,R.drawable.blog,R.drawable.reachus};
        String[] titles = {"PRODUCTS", "ABOUT US ", "BLOG", "REACH US"};
        for (int i=0;i<titles.length && i<icons.length;i++){
            Info current = new Info();
            current.iconId = icons[i];
            current.title = titles[i];
            data.add(current);
        }
        return data;
    }

    public void setUp(int fragmentId,DrawerLayout drawerLayout, final Toolbar toolbar) {
        containerView = getActivity().findViewById(fragmentId);
        sDrawerLayout = drawerLayout;
        sDrawerToggle = new ActionBarDrawerToggle(getActivity(), drawerLayout, toolbar, R.string.drawer_open,R.string.drawer_close){

            @Override
            public void onDrawerOpened(View drawerView) {
                super.onDrawerOpened(drawerView);
                if (!sUserLearnedDrawer){
                    sUserLearnedDrawer = true;
                    saveToPreferences(getActivity(), KEY_USER_LEARNED_DRAWER, sUserLearnedDrawer+"");
                }
                getActivity().invalidateOptionsMenu();
            }

            @Override
            public void onDrawerClosed(View drawerView) {
                super.onDrawerClosed(drawerView);
                getActivity().invalidateOptionsMenu();
            }

            @Override
            public void onDrawerSlide(View drawerView, float slideOffset) {
                if (slideOffset < 0.5){
                    toolbar.setAlpha(1-slideOffset);
                }
            }
        };
        if (!sUserLearnedDrawer && !sFromSavedInstanceState){
            sDrawerLayout.openDrawer(containerView);
        }
        sDrawerLayout.setDrawerListener(sDrawerToggle);
        sDrawerLayout.post(new Runnable() {
            @Override
            public void run() {
           sDrawerToggle.syncState();
            }
        });
    }
public static void saveToPreferences(Context conrext, String preferenceName, String preferenceValue){

    SharedPreferences sP = conrext.getSharedPreferences(PREF_FILE_NAME, conrext.MODE_PRIVATE);
    SharedPreferences.Editor editor = sP.edit();
    editor.putString(preferenceName, preferenceValue);
    editor.apply();
}
    public static String readFromPreferences(Context context, String preferenceName, String defaultValue){
        SharedPreferences sP = context.getSharedPreferences(PREF_FILE_NAME, context.MODE_PRIVATE);
        return sP.getString(preferenceName,defaultValue);
    }

    class RecyclerTouchListener implements RecyclerView.OnItemTouchListener {

        private GestureDetector gestureDetector;
        private ClickListener clickListener;
        public RecyclerTouchListener(Context context, final RecyclerView recyclerView, final ClickListener clickListener){

        this.clickListener = clickListener;
        gestureDetector = new GestureDetector(context, new GestureDetector.SimpleOnGestureListener(){
            @Override
            public boolean onSingleTapUp(MotionEvent e) {
                return true;
            }

            @Override
            public void onLongPress(MotionEvent e) {
                View child = recyclerView.findChildViewUnder(e.getX(), e.getY());
                if (child != null && clickListener != null){
                    clickListener.onLongClick(child, recyclerView.getChildPosition(child));
                }
            }
        });
        }

        @Override
        public boolean onInterceptTouchEvent(RecyclerView rv, MotionEvent e) {
            View child = rv.findChildViewUnder(e.getX(), e.getY());
            if (child != null && clickListener != null && gestureDetector.onTouchEvent(e)){
                clickListener.onClick(child, rv.getChildPosition(child));
            }
            return false;
        }

        @Override
        public void onTouchEvent(RecyclerView rv, MotionEvent e) {

        }

        @Override
        public void onRequestDisallowInterceptTouchEvent(boolean disallowIntercept) {

        }
    }

    public interface ClickListener {
        public  void onClick(View view, int posititon);
        public void onLongClick(View view, int position);
    }
}

logcat的:

FATAL EXCEPTION: main
12-08 12:50:20.750 5400-5400/com.sun.suni.design E/AndroidRuntime: Process: com.sun.suni.design, PID: 5400
12-08 12:50:20.750 5400-5400/com.sun.suni.design E/AndroidRuntime: java.lang.NullPointerException: Attempt to invoke virtual method 'boolean android.support.v7.widget.RecyclerView$ViewHolder.shouldIgnore()' on a null object reference
12-08 12:50:20.750 5400-5400/com.sun.suni.design E/AndroidRuntime:     at android.support.v7.widget.RecyclerView.findMinMaxChildLayoutPositions(RecyclerView.java:2978)
12-08 12:50:20.750 5400-5400/com.sun.suni.design E/AndroidRuntime:     at android.support.v7.widget.RecyclerView.dispatchLayout(RecyclerView.java:2824)
12-08 12:50:20.750 5400-5400/com.sun.suni.design E/AndroidRuntime:     at android.support.v7.widget.RecyclerView.onLayout(RecyclerView.java:3071)
12-08 12:50:20.750 5400-5400/com.sun.suni.design E/AndroidRuntime:     at android.view.View.layout(View.java:15596)
12-08 12:50:20.750 5400-5400/com.sun.suni.design E/AndroidRuntime:     at android.view.ViewGroup.layout(ViewGroup.java:4966)
12-08 12:50:20.750 5400-5400/com.sun.suni.design E/AndroidRuntime:     at android.widget.RelativeLayout.onLayout(RelativeLayout.java:1076)
12-08 12:50:20.750 5400-5400/com.sun.suni.design E/AndroidRuntime:     at android.view.View.layout(View.java:15596)
12-08 12:50:20.750 5400-5400/com.sun.suni.design E/AndroidRuntime:     at android.view.ViewGroup.layout(ViewGroup.java:4966)
12-08 12:50:20.750 5400-5400/com.sun.suni.design E/AndroidRuntime:     at android.support.v4.widget.DrawerLayout.onLayout(DrawerLayout.java:1067)
12-08 12:50:20.750 5400-5400/com.sun.suni.design E/AndroidRuntime:     at android.view.View.layout(View.java:15596)
12-08 12:50:20.750 5400-5400/com.sun.suni.design E/AndroidRuntime:     at android.view.ViewGroup.layout(ViewGroup.java:4966)
12-08 12:50:20.750 5400-5400/com.sun.suni.design E/AndroidRuntime:     at android.widget.FrameLayout.layoutChildren(FrameLayout.java:573)
12-08 12:50:20.750 5400-5400/com.sun.suni.design E/AndroidRuntime:     at android.widget.FrameLayout.onLayout(FrameLayout.java:508)
12-08 12:50:20.750 5400-5400/com.sun.suni.design E/AndroidRuntime:     at android.view.View.layout(View.java:15596)
12-08 12:50:20.750 5400-5400/com.sun.suni.design E/AndroidRuntime:     at android.view.ViewGroup.layout(ViewGroup.java:4966)
12-08 12:50:20.750 5400-5400/com.sun.suni.design E/AndroidRuntime:     at android.widget.LinearLayout.setChildFrame(LinearLayout.java:1703)
12-08 12:50:20.750 5400-5400/com.sun.suni.design E/AndroidRuntime:     at android.widget.LinearLayout.layoutVertical(LinearLayout.java:1557)
12-08 12:50:20.750 5400-5400/com.sun.suni.design E/AndroidRuntime:     at android.widget.LinearLayout.onLayout(LinearLayout.java:1466)
12-08 12:50:20.750 5400-5400/com.sun.suni.design E/AndroidRuntime:     at android.view.View.layout(View.java:15596)
12-08 12:50:20.750 5400-5400/com.sun.suni.design E/AndroidRuntime:     at android.view.ViewGroup.layout(ViewGroup.java:4966)
12-08 12:50:20.750 5400-5400/com.sun.suni.design E/AndroidRuntime:     at android.widget.FrameLayout.layoutChildren(FrameLayout.java:573)
12-08 12:50:20.750 5400-5400/com.sun.suni.design E/AndroidRuntime:     at android.widget.FrameLayout.onLayout(FrameLayout.java:508)
12-08 12:50:20.750 5400-5400/com.sun.suni.design E/AndroidRuntime:     at android.view.View.layout(View.java:15596)
12-08 12:50:20.750 5400-5400/com.sun.suni.design E/AndroidRuntime:     at android.view.ViewGroup.layout(ViewGroup.java:4966)
12-08 12:50:20.750 5400-5400/com.sun.suni.design E/AndroidRuntime:     at android.widget.LinearLayout.setChildFrame(LinearLayout.java:1703)
12-08 12:50:20.750 5400-5400/com.sun.suni.design E/AndroidRuntime:     at android.widget.LinearLayout.layoutVertical(LinearLayout.java:1557)
12-08 12:50:20.750 5400-5400/com.sun.suni.design E/AndroidRuntime:     at android.widget.LinearLayout.onLayout(LinearLayout.java:1466)
12-08 12:50:20.750 5400-5400/com.sun.suni.design E/AndroidRuntime:     at android.view.View.layout(View.java:15596)
12-08 12:50:20.750 5400-5400/com.sun.suni.design E/AndroidRuntime:     at android.view.ViewGroup.layout(ViewGroup.java:4966)
12-08 12:50:20.750 5400-5400/com.sun.suni.design E/AndroidRuntime:     at android.widget.FrameLayout.layoutChildren(FrameLayout.java:573)
12-08 12:50:20.750 5400-5400/com.sun.suni.design E/AndroidRuntime:     at android.widget.FrameLayout.onLayout(FrameLayout.java:508)
12-08 12:50:20.750 5400-5400/com.sun.suni.design E/AndroidRuntime:     at android.view.View.layout(View.java:15596)
12-08 12:50:20.750 5400-5400/com.sun.suni.design E/AndroidRuntime:     at android.view.ViewGroup.layout(ViewGroup.java:4966)
12-08 12:50:20.750 5400-5400/com.sun.suni.design E/AndroidRuntime:     at android.view.ViewRootImpl.performLayout(ViewRootImpl.java:2072)
12-08 12:50:20.750 5400-5400/com.sun.suni.design E/AndroidRuntime:     at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:1829)
12-08 12:50:20.750 5400-5400/com.sun.suni.design E/AndroidRuntime:     at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:1054)
12-08 12:50:20.750 5400-5400/com.sun.suni.design E/AndroidRuntime:     at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:5779)
12-08 12:50:20.750 5400-5400/com.sun.suni.design E/AndroidRuntime:     at android.view.Choreographer$CallbackRecord.run(Choreographer.java:767)
12-08 12:50:20.750 5400-5400/com.sun.suni.design E/AndroidRuntime:     at android.view.Choreographer.doCallbacks(Choreographer.java:580)
12-08 12:50:20.750 5400-5400/com.sun.suni.design E/AndroidRuntime:     at android.view.Choreographer.doFrame(Choreographer.java:550)
12-08 12:50:20.750 5400-5400/com.sun.suni.design E/AndroidRuntime:     at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:753)
12-08 12:50:20.750 5400-5400/com.sun.suni.design E/AndroidRuntime:     at android.os.Handler.handleCallback(Handler.java:739)
12-08 12:50:20.750 5400-5400/com.sun.suni.design E/AndroidRuntime:     at android.os.Handler.dispatchMessage(Handler.java:95)

SunAdapter:

import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import java.util.Collections;
import java.util.List;

/**
 * Created by CloudicaLabs on 12/1/2015.
 */
public class SunAdapter extends RecyclerView.Adapter<SunAdapter.MyViewHolder> {

    private LayoutInflater inflater;
    List<Info> data = Collections.emptyList();

    public SunAdapter(Context context, List<Info> data) {
        inflater = LayoutInflater.from(context);
        this.data = data;
    }

    @Override
    public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View view = inflater.inflate(R.layout.custom_row, parent, false);
        MyViewHolder holder = new MyViewHolder(view);
        return holder;
    }

    @Override
    public void onBindViewHolder(MyViewHolder holder, int position) {
        Info current = data.get(position);
        holder.title.setText(current.title);
        holder.icon.setImageResource(current.iconId);
    }

    @Override
    public int getItemCount() {
        return data.size();
    }

    class MyViewHolder extends RecyclerView.ViewHolder {

        TextView title;
        ImageView icon;

        public MyViewHolder(View itemView) {
            super(itemView);
            title = (TextView) itemView.findViewById(R.id.listText);
            icon = (ImageView) itemView.findViewById(R.id.listIcon);
        }
    }
}

1 个答案:

答案 0 :(得分:0)

问题出在这里

fragmentManager.beginTransaction().replace(R.id.drawer_list, fragment).commit();

您正在替换Recyclerview内的片段。因此,在第一个参数中,您需要提供FrameLayout的资源ID。