使用tablayout内部片段实现recyclerview

时间:2017-12-29 08:07:58

标签: android android-recyclerview fragment android-tablayout

如何在片段内部Recyclerview实施TabLayout? 之前我已成功使用RecyclerviewTabLayout的活动。但是当我尝试在片段旁边使用TabLayout时,Recyclerview没有显示。

我已尝试查看教程参考资料如下:

link

但我没有成功。 在这里,我附上了我的代码片段,标签片段:

TabAddFragment1.java

package com.mimdudin.carekkerje.Activities;


import android.content.Context;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.app.Fragment;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;

import com.android.volley.AuthFailureError;
import com.android.volley.NetworkError;
import com.android.volley.NoConnectionError;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.TimeoutError;
import com.android.volley.VolleyError;
import com.android.volley.VolleyLog;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.StringRequest;
import com.mimdudin.carekkerje.Adapter.AddRecyclerViewadapter;
import com.mimdudin.carekkerje.Helper.AppController;
import com.mimdudin.carekkerje.Model.Add;
import com.mimdudin.carekkerje.R;
import com.mimdudin.carekkerje.Util.Constant;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static com.android.volley.VolleyLog.TAG;

/**
 * A simple {@link Fragment} subclass.
 */
public class TabAddFragment1 extends Fragment {
    private RecyclerView recyclerView;
    private AddRecyclerViewadapter addRecyclerViewadapter;
    private List<Add> addList;
    private SharedPreferences sharedPreferences;
    private String apiKey;
    public TabAddFragment1() {
        // Required empty public constructor
    }


    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this
        View view = inflater.inflate(R.layout.tabadd1, container, false);

        recyclerView = view.findViewById(R.id.recyclerViewAdd);
        recyclerView.setHasFixedSize(true);
        recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));

        addList = new ArrayList<>();
        addList = getAdd();

        addRecyclerViewadapter = new AddRecyclerViewadapter(getContext(), addList);
        recyclerView.setAdapter(addRecyclerViewadapter);
        addRecyclerViewadapter.notifyDataSetChanged();

        sharedPreferences = getActivity().getSharedPreferences("data", Context.MODE_PRIVATE);

        return view;
    }

    private List<Add> getAdd() {
        String tag_headers_req = "req_apikey";
        JsonObjectRequest jsonObjRequest = new JsonObjectRequest(Request.Method.GET, Constant.URL_GETADD, null,
                new Response.Listener<JSONObject>() {
                    @Override
                    public void onResponse(JSONObject response) {
                        Log.d("onResponse: ", response.toString());

                        try {
                            boolean error = response.getBoolean("error");

                            if (!error){
                                JSONArray jsonArr = response.getJSONArray("transaksi");
                                for (int i = 0; i < jsonArr.length(); i++){
                                    JSONObject allObj = jsonArr.getJSONObject(i);

                                    Add add = new Add();
                                    add.setTitleAdd(allObj.getString("title"));
                                    add.setPreviewAdd(allObj.getString("deskripsi"));
                                    add.setTanggalAdd(allObj.getString("tanggal"));
                                    add.setImg_logoAdd(allObj.getString("img_logo"));

                                    SharedPreferences.Editor editor = sharedPreferences.edit();
                                    editor.putString("title", add.getTitleAdd());
                                    editor.putString("deskripsi", add.getPreviewAdd());
                                    editor.putString("tanggal", add.getTanggalAdd());
                                    editor.putString("img_logo", add.getImg_logoAdd());
                                    editor.commit();

                                    addList.add(add);
                                }
                            } else {
                                Toast.makeText(getContext(), response.getString("message"), Toast.LENGTH_SHORT).show();
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                            Log.d(TAG, "onResponse: " + e.getMessage());
                        }
                    }
                }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                VolleyLog.d("Error: " + error.getMessage());
                if (error instanceof TimeoutError || error instanceof NoConnectionError || error instanceof NetworkError){
                    Toast.makeText(getContext(), "Please check your connection!", Toast.LENGTH_SHORT).show();
                }
            }
        })
        {
            @Override
            public String getBodyContentType() {
                return "application/x-www-form-urlencoded";
            }

            @Override
            public Map<String, String> getHeaders() throws AuthFailureError {
                Map<String, String> headers = new HashMap<>();
                sharedPreferences = getActivity().getSharedPreferences("data", Context.MODE_PRIVATE);
                apiKey = sharedPreferences.getString("apiKey", "User Tidak Ditemukan");
                Log.d("getHeaders: ", apiKey);

//                headers.put("Content-Type", "application/json; charset=utf-8");
//                headers.put("Content-Type", "application/x-www-form-urlencoded");

                headers.put("Authorization", apiKey);
                return headers;
            }
        };
        AppController.getInstance().addToRequestQueue(jsonObjRequest, tag_headers_req);
        return  addList;
    }
}

AND,我的recyclerview适配器

AddRecyclerviewAdapter.java

package com.mimdudin.carekkerje.Adapter;

import android.content.Context;
import android.os.Bundle;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.app.AppCompatActivity;
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 com.bumptech.glide.Glide;
import com.bumptech.glide.request.RequestOptions;
import com.mimdudin.carekkerje.Activities.TabAddFragment1Detail;
import com.mimdudin.carekkerje.Model.Add;
import com.mimdudin.carekkerje.R;

import java.util.List;

public class AddRecyclerViewadapter extends RecyclerView.Adapter<AddRecyclerViewadapter.ViewHolder> {
    private Context context;
    private List<Add> addList;

    public AddRecyclerViewadapter(Context context, List<Add> addList){
        this.context = context;
        this.addList = addList;
    }

    @Override
    public AddRecyclerViewadapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(parent.getContext())
                .inflate(R.layout.add_row, parent, false);
        return new ViewHolder(view, context);
    }

    @Override
    public void onBindViewHolder(AddRecyclerViewadapter.ViewHolder holder, int position) {
        Add add = addList.get(position);

        holder.tvTitleAdd.setText(add.getTitleAdd());
        holder.tvPreviewAdd.setText(add.getPreviewAdd());
        holder.tvTanggalAdd.setText(add.getTanggalAdd());

        String img_logoAddurl = add.getImg_logoAdd();
        Glide.with(context)
                .load(img_logoAddurl)
                .apply(new RequestOptions().placeholder(android.R.drawable.ic_dialog_info)
                        .error(android.R.drawable.ic_dialog_alert).centerCrop().dontAnimate()
//                         .centerCrop(), .crossFade(), .thumbnail(), .dontAnimate(), .dontTransform() BitmapTransformation(.circleCrop())
        )
                .into(holder.img_logoAdd);

    }

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

    public class ViewHolder extends RecyclerView.ViewHolder {
        private TextView tvTitleAdd;
        private TextView tvPreviewAdd;
        private ImageView img_logoAdd;
        private TextView tvTanggalAdd;

        public ViewHolder(final View itemView, final Context ctx) {
            super(itemView);
            context = ctx;

            tvTitleAdd = itemView.findViewById(R.id.tvTitleAdd);
            tvPreviewAdd = itemView.findViewById(R.id.tvPreviewAdd);
            img_logoAdd = itemView.findViewById(R.id.img_logoAdd);
            tvTanggalAdd = itemView.findViewById(R.id.tvTanggalAdd);

            itemView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {

                    TabAddFragment1Detail tabAddFragment1Detail = new TabAddFragment1Detail();

                    Add add = addList.get(getAdapterPosition());
                    Bundle bundle = new Bundle();
                    bundle.putSerializable("add", add);
                    tabAddFragment1Detail.setArguments(bundle);

                    AppCompatActivity activity = (AppCompatActivity) itemView.getContext();

                    android.support.v4.app.FragmentManager fragmentManager = activity.getSupportFragmentManager();
                    FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction().addToBackStack(null);
//                    fragmentTransaction.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE);
                    fragmentTransaction.replace(R.id.frame_fragmentaddDetail, tabAddFragment1Detail);
                    fragmentTransaction.commit();

                }
            });
        }
    }
}

并且,在这里我附上播放tablayout,他们初始化标签片段

AddFragment.java

package com.mimdudin.carekkerje.Activities;


import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentStatePagerAdapter;
import android.support.v4.view.ViewPager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.mimdudin.carekkerje.R;

/**
 * A simple {@link Fragment} subclass.
 */
public class AddFragment extends Fragment {
    public AddFragment() {
        // Required empty public constructor
    }

    //untuk bottom navigation
    public static AddFragment newInstance() {
        return new AddFragment();
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
         View view = inflater.inflate(R.layout.fragment_add, container, false);

//        Toolbar toolbar = view.findViewById(R.id.toolbar);
//        ((AppCompatActivity)getActivity()).setSupportActionBar(toolbar);

        TabLayout tabLayout = view.findViewById(R.id.tabLayout);
        tabLayout.addTab(tabLayout.newTab().setText("Pasang"));
        tabLayout.addTab(tabLayout.newTab().setText("History"));
        tabLayout.setTabGravity(TabLayout.GRAVITY_FILL);

        final ViewPager viewPager = view.findViewById(R.id.pagerAdd);
//        tabLayout.setupWithViewPager(viewPager);
        final AddPagerAdapter adapter = new AddPagerAdapter(getActivity().getSupportFragmentManager(), tabLayout.getTabCount());
        viewPager.setAdapter(adapter);

        viewPager.setOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout));
        tabLayout.setOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
            @Override
            public void onTabSelected(TabLayout.Tab tab) {
                viewPager.setCurrentItem(tab.getPosition());
            }

            @Override
            public void onTabUnselected(TabLayout.Tab tab) {

            }

            @Override
            public void onTabReselected(TabLayout.Tab tab) {

            }
        });

        return view;

    }

    private class AddPagerAdapter extends FragmentStatePagerAdapter {

        private int tabCount;

        AddPagerAdapter(FragmentManager fm, int tabCount) {
            super(fm);
            this.tabCount = tabCount;
        }

        @Override
        public Fragment getItem(int position) {
            switch (position){
                case 0:
                    return new TabAddFragment2();
                case 1:
                    return new TabAddFragment1();
                default:
                    return null;
            }
        }

        @Override
        public int getCount() {
            return tabCount;
        }
    }

}
希望你能帮我解决。

1 个答案:

答案 0 :(得分:1)

如果您想使用嵌套fragment而不是

使用 getChildFragmentManager() 而不是 getSupportFragmentManager()

使用此

 final AddPagerAdapter adapter = new AddPagerAdapter(getChildFragmentManager(), tabLayout.getTabCount());

而不是

 final AddPagerAdapter adapter = new AddPagerAdapter(getActivity().getSupportFragmentManager(), tabLayout.getTabCount());
在列表中添加数据后,notifyDataSetChanged()中的

编辑 getAdd()

试试这个

 addRecyclerViewadapter.notifyDataSetChanged();

<强> CODE

private List<Add> getAdd() {
        String tag_headers_req = "req_apikey";
        JsonObjectRequest jsonObjRequest = new JsonObjectRequest(Request.Method.GET, Constant.URL_GETADD, null,
                new Response.Listener<JSONObject>() {
                    @Override
                    public void onResponse(JSONObject response) {
                        Log.d("onResponse: ", response.toString());

                        try {
                            boolean error = response.getBoolean("error");

                            if (!error){
                                JSONArray jsonArr = response.getJSONArray("transaksi");
                                for (int i = 0; i < jsonArr.length(); i++){
                                    JSONObject allObj = jsonArr.getJSONObject(i);

                                    Add add = new Add();
                                    add.setTitleAdd(allObj.getString("title"));
                                    add.setPreviewAdd(allObj.getString("deskripsi"));
                                    add.setTanggalAdd(allObj.getString("tanggal"));
                                    add.setImg_logoAdd(allObj.getString("img_logo"));

                                    SharedPreferences.Editor editor = sharedPreferences.edit();
                                    editor.putString("title", add.getTitleAdd());
                                    editor.putString("deskripsi", add.getPreviewAdd());
                                    editor.putString("tanggal", add.getTanggalAdd());
                                    editor.putString("img_logo", add.getImg_logoAdd());
                                    editor.commit();

                                    addList.add(add);
                                }
                               // add here  notifyDataSetChanged(); 
                                addRecyclerViewadapter.notifyDataSetChanged();
                            } else {
                                Toast.makeText(getContext(), response.getString("message"), Toast.LENGTH_SHORT).show();
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                            Log.d(TAG, "onResponse: " + e.getMessage());
                        }
                    }
                }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                VolleyLog.d("Error: " + error.getMessage());
                if (error instanceof TimeoutError || error instanceof NoConnectionError || error instanceof NetworkError){
                    Toast.makeText(getContext(), "Please check your connection!", Toast.LENGTH_SHORT).show();
                }
            }
        })
        {
            @Override
            public String getBodyContentType() {
                return "application/x-www-form-urlencoded";
            }

            @Override
            public Map<String, String> getHeaders() throws AuthFailureError {
                Map<String, String> headers = new HashMap<>();
                sharedPreferences = getActivity().getSharedPreferences("data", Context.MODE_PRIVATE);
                apiKey = sharedPreferences.getString("apiKey", "User Tidak Ditemukan");
                Log.d("getHeaders: ", apiKey);

//                headers.put("Content-Type", "application/json; charset=utf-8");
//                headers.put("Content-Type", "application/x-www-form-urlencoded");

                headers.put("Authorization", apiKey);
                return headers;
            }
        };
        AppController.getInstance().addToRequestQueue(jsonObjRequest, tag_headers_req);
        return  addList;
    }