>source

5 개의 프래그먼트가 있고 하단 네비게이션 바가 표시됩니다. 첫 번째 조각을 조각 A라고 부를 수 있습니다. 나는 발리를 사용하여 조각에서 데이터를로드하고 재활용보기를 사용하여 표시합니다. 다른 조각 (조각 B)으로 아래쪽 탐색을 클릭하고 조각 A를 다시 클릭하면 데이터가 사라집니다.

하단 탐색 조각이 포함 된 주요 활동 :

protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        if(isNetworkStatusAvialable (getApplicationContext())) {
            bottomNavigationView=(BottomNavigationView)findViewById(R.id.main_nav);
            frameLayout=(FrameLayout) findViewById(R.id.main_frame);
            herbal= new herbal();
            crude = new crude();
            database=new database();
            analysis=new analysis();
            compound=new compound();
            setFragment(herbal);
            bottomNavigationView.setOnNavigationItemSelectedListener(new BottomNavigationView.OnNavigationItemSelectedListener() {
                @Override
                public boolean onNavigationItemSelected(@NonNull MenuItem menuItem) {
                    switch (menuItem.getItemId())
                    {
                        case R.id.nav_herbal:
                            setFragment(herbal);
                            return true;
                        case R.id.nav_crude:
                            setFragment(crude);
                            return true;
                        case R.id.nav_database:
                            setFragment(database);
                            return true;
                        case R.id.nav_analysis:
                            setFragment(analysis);
                            return true;
                        case R.id.nav_compound:
                            setFragment(compound);
                            return true;
                        default:
                            return false;
                    }
                }

            });
        } else {
            Toast.makeText(getApplicationContext(), "internet is not avialable", Toast.LENGTH_SHORT).show();
        }

    }
    private boolean isNetworkStatusAvialable(Context context) {
        ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        if (connectivityManager != null)
        {
            NetworkInfo netInfos = connectivityManager.getActiveNetworkInfo();
            if(netInfos != null)
                if(netInfos.isConnected())
                    return true;
        }
        return false;
    }
    private void setFragment(Fragment fragment) {
        FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
        fragmentTransaction.replace(R.id.main_frame,fragment);
        fragmentTransaction.commit();
    }

이것은 recyclerview 프래그먼트 A의 코드입니다 :

public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View rootView = inflater.inflate(R.layout.fragment_herbal, container, false);
        herbalModels = new ArrayList<>();
        kampoModels = new ArrayList<>();
        searchHerbal = (EditText) rootView.findViewById(R.id.search_herbal);
        searchHerbal.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                searchHerb();
            }
        });
        loadData = (ProgressBar) rootView.findViewById(R.id.loadRecyclerView);
        RequestQueue queue = MySingleton.getInstance(this.getActivity().getApplicationContext()).getRequestQueue();
        sortData(rootView);
        get20DataJamu();
        get20DataKampo();
        StartRecyclerViewJamu(rootView);

        return rootView;
    }
    private void searchHerb() {
        FragmentManager fm = getFragmentManager();
        FragmentTransaction ft = fm.beginTransaction();
        searchHerbs searchHerbs = new searchHerbs();
        ft.replace(R.id.main_frame, searchHerbs);
        ft.commit();
    }

    private void StartRecyclerViewKampo(View rootView) {
        mRecyclerView = (RecyclerView) rootView.findViewById(R.id.recyclerview_herbal);
        mRecyclerView.setHasFixedSize(true);
        mLayoutManager = new LinearLayoutManager(getActivity());
        // use a linear layout manager
        mRecyclerView.setLayoutManager(mLayoutManager);
        kampoAdapter = new kampoAdapter(mRecyclerView, getActivity(), kampoModels);
        mRecyclerView.setAdapter(kampoAdapter);
        kampoAdapter.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore() {
                kampoModels.add(null);
                kampoAdapter.notifyItemInserted(kampoModels.size() - 1);
                handler = new Handler();
                handler.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        kampoModels.remove(kampoModels.size() - 1);
                        kampoAdapter.notifyItemRemoved(kampoModels.size());
                        //add items one by one
                        int start = kampoModels.size();
                        int end = start + 20;
                        loadMoreKampo(start, end);
                    }
                }, 5000);
            }
        });
    }
    private void loadMoreKampo(final int start, final int end) {
        String url = "https://jsonplaceholder.typicode.com/photos";
        JsonArrayRequest request = new JsonArrayRequest(url,
                new Response.Listener<JSONArray>() {
                    @Override
                    public void onResponse(JSONArray jsonArray) {
                        Log.d(TAG, "Onresponse" + jsonArray.toString());
                        for (int i = start; i < end; i++) {
                            try {
                                JSONObject jsonObject = jsonArray.getJSONObject(i);
//                                Log.d(TAG,"jsonobject"+jsonObject);
                                kampoModels.add(
                                        new kampoModel(
                                                jsonObject.getString("title"),
                                                "Khasiat",
                                                jsonObject.getString("albumId"),
                                                jsonObject.getString("id"),
                                                jsonObject.getString("thumbnailUrl")
                                        )
                                );
                                kampoAdapter.notifyItemInserted(kampoModels.size());
                            } catch (JSONException e) {
                            }
                        }
                        kampoAdapter.setLoaded();
                    }
                },
                new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError volleyError) {
                        Log.d(TAG, "Onerror" + volleyError.toString());
                    }
                });
        MySingleton.getInstance(getActivity()).addToRequestQueue(request);
    }
    private void get20DataKampo() {
        String url = "https://jsonplaceholder.typicode.com/photos";
        JsonArrayRequest request = new JsonArrayRequest(url,
                new Response.Listener<JSONArray>() {
                    @Override
                    public void onResponse(JSONArray jsonArray) {
                        Log.d(TAG, "Onresponsekampo" + jsonArray.toString());
                        Log.d(TAG, "lengthresponse" + jsonArray.length());
                        for (int i = 0; i < 20; i++) {
                            try {
                                JSONObject jsonObject = jsonArray.getJSONObject(i);
//                                Log.d(TAG,"jsonobject"+jsonObject);
                                kampoModels.add(
                                        new kampoModel(
                                                jsonObject.getString("title"),
                                                "Khasiat",
                                                jsonObject.getString("albumId"),
                                                jsonObject.getString("id"),
                                                jsonObject.getString("thumbnailUrl")
                                        )
                                );
                            } catch (JSONException e) {
                            }
                        }
                    }
                },
                new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError volleyError) {
                        Log.d(TAG, "Onerrorkampo" + volleyError.toString());
                    }
                });
        MySingleton.getInstance(getActivity()).addToRequestQueue(request);
    }

    private void StartRecyclerViewJamu(final View rootView) {
        mRecyclerView = (RecyclerView) rootView.findViewById(R.id.recyclerview_herbal);
        mRecyclerView.setVisibility(View.GONE);
        mRecyclerView.setHasFixedSize(true);
        mLayoutManager = new LinearLayoutManager(getActivity());
        // use a linear layout manager
        mRecyclerView.setLayoutManager(mLayoutManager);
        // create an Object for Adapter
        mAdapter = new herbalAdapter(mRecyclerView, getActivity(), herbalModels);
        mRecyclerView.setAdapter(mAdapter);
        loadData.setVisibility(View.GONE);
        mRecyclerView.setVisibility(View.VISIBLE);
        mAdapter.notifyDataSetChanged();
        mAdapter.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore() {
                //add null , so the adapter will check view_type and show progress bar at bottom
                herbalModels.add(null);
                mAdapter.notifyItemInserted(herbalModels.size() - 1);
                handler = new Handler();
                handler.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        //   remove progress item
                        herbalModels.remove(herbalModels.size() - 1);
                        mAdapter.notifyItemRemoved(herbalModels.size());
                        //add items one by one
                        int start = herbalModels.size();
                        int end = start + 20;
                        loadMoreJamu(start, end);
                    }
                }, 5000);
            }
        });

    }
    private void get20DataJamu() {
        String url = "https://jsonplaceholder.typicode.com/posts";
        JsonArrayRequest request = new JsonArrayRequest(url,
                new Response.Listener<JSONArray>() {
                    @Override
                    public void onResponse(JSONArray jsonArray) {
                        Log.d(TAG, "Onresponse" + jsonArray.toString());
                        Log.d(TAG, "lengthonresponse" + jsonArray.length());
                        for (int i = 0; i < 20; i++) {
                            try {
                                JSONObject jsonObject = jsonArray.getJSONObject(i);
//                                Log.d(TAG,"jsonobject"+jsonObject);
                                herbalModels.add(
                                        new herbalModel(
                                                jsonObject.getString("title"),
                                                "Khasiat",
                                                jsonObject.getString("userId"),
                                                jsonObject.getString("id"),
                                                jsonObject.getString("body")
                                        )
                                );
                            } catch (JSONException e) {
                            }
                        }
                    }
                },
                new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError volleyError) {
                        Log.d(TAG, "Onerror" + volleyError.toString());
                    }
                });
        MySingleton.getInstance(getActivity()).addToRequestQueue(request);
    }

    private void loadMoreJamu(final int start, final int end) {
        String url = "https://jsonplaceholder.typicode.com/posts";
        JsonArrayRequest request = new JsonArrayRequest(url,
                new Response.Listener<JSONArray>() {
                    @Override
                    public void onResponse(JSONArray jsonArray) {
                        Log.d(TAG, "Onresponse" + jsonArray.toString());
                        for (int i = start; i < end; i++) {
                            try {
                                JSONObject jsonObject = jsonArray.getJSONObject(i);
//                                Log.d(TAG,"jsonobject"+jsonObject);
                                herbalModels.add(
                                        new herbalModel(
                                                jsonObject.getString("title"),
                                                "Khasiat",
                                                jsonObject.getString("userId"),
                                                jsonObject.getString("id"),
                                                jsonObject.getString("body")
                                        )
                                );
                                mAdapter.notifyItemInserted(herbalModels.size());
                            } catch (JSONException e) {
                            }
                        }
                        mAdapter.setLoaded();
                    }
                },
                new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError volleyError) {
                        Log.d(TAG, "Onerror" + volleyError.toString());
                    }
                });
        MySingleton.getInstance(getActivity()).addToRequestQueue(request);
    }
    private void sortData(final View rootView) {
        final Spinner spinner = (Spinner) rootView.findViewById(R.id.filter_herbal);
// Create an ArrayAdapter using the string array and a default spinner layout
        List<categoriesHerbal> itemList = new ArrayList<categoriesHerbal>();
        itemList.add(
                new categoriesHerbal(
                        "1",
                        "Jamu"
                )
        );
        itemList.add(
                new categoriesHerbal(
                        "2",
                        "Kampo"
                )
        );
        ArrayAdapter<categoriesHerbal> spinnerAdapter = new ArrayAdapter<categoriesHerbal>(getActivity(), android.R.layout.simple_spinner_item, itemList);
        spinnerAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
// Specify the layout to use when the list of choices appears
// Apply the adapter to the spinner
        spinner.setAdapter(spinnerAdapter);
        spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                if (position == 0) {
                    categoriesHerbal selectedValue = (categoriesHerbal) parent.getItemAtPosition(position);
                    String categories = (String) selectedValue.getCategories();
                    String idCategories = (String) selectedValue.getIdCategories();
                    StartRecyclerViewJamu(rootView);
                } else {
                    categoriesHerbal selectedValue = (categoriesHerbal) parent.getItemAtPosition(position);
                    String categories = (String) selectedValue.getCategories();
                    String idCategories = (String) selectedValue.getIdCategories();
                    StartRecyclerViewKampo(rootView);
                }
            }
            @Override
            public void onNothingSelected(AdapterView<?> parent) {
            }
        });
    }

}


  • 답변 # 1

    setFragment ()를

    private void setFragment(Fragment fragment) {
            FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
            fragmentTransaction.add(R.id.main_frame,fragment);
    fragmentTransaction.addToBackStack(null);
            fragmentTransaction.commit();
        } 
    
    

    그리고 돌아 오려면 마지막 조각을 제거하십시오.

관련 자료

  • 이전 android - Firebase에서 데이터를 검색하여 recyclerview에서 표시하는 방법은 무엇입니까?
  • 다음 html - 가로 50 %에서 시작하는 100 % 높이 배경