Переключение между фрагментами в макете с BottomNavigationView - PullRequest
0 голосов
/ 04 июня 2018

Это моя первая попытка разработать приложение для Android.

У меня есть MainActivity с ConstraintLayout, который имеет BottomNavigationView.Всякий раз, когда выбирается первый элемент навигации, я хочу отобразить список категорий (отображаемых во фрагменте), затем всякий раз, когда эта категория выбирается, будет отображаться другой список для элементов, относящихся к этой конкретной категории (в другом фрагменте).

Я прочитал ( Android - фрагмент .replace () не заменяет контент - помещает его поверх ), где говорится, что «статические фрагменты, написанные на XML, не могут быть заменены,это должно быть в контейнере фрагмента ", как это выглядит?

Я попытался создать свой контейнер фрагмента, но что-то не так, когда я пытаюсь получить ListView (дочерний элемент контейнера)

CategoriesListView = getView (). FindViewById (R.id.categoriesList);

возвращает ноль.

MainActivity

package com.alsowaygh.getitdone.view.main;

import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.design.widget.BottomNavigationView;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.MenuItem;
import android.widget.TextView;


import com.alsowaygh.getitdone.R;
import com.alsowaygh.getitdone.view.services.CategoriesListFragment;
import com.alsowaygh.getitdone.view.services.OnCategorySelectedListener;
import com.alsowaygh.getitdone.view.services.ServicesListFragment;

public class MainActivity extends AppCompatActivity implements OnCategorySelectedListener {

    private static final String TAG = "MainActivity";
    FragmentManager fragmentManager;
    FragmentTransaction fragmentTransaction;


    private BottomNavigationView.OnNavigationItemSelectedListener mOnNavigationItemSelectedListener
            = new BottomNavigationView.OnNavigationItemSelectedListener() {

        @Override
        public boolean onNavigationItemSelected(@NonNull MenuItem item) {
            switch (item.getItemId()) {
                case R.id.navigation_services:
//                    mTextMessage.setText(R.string.title_services);
                    CategoriesListFragment categoriesListFragment = new CategoriesListFragment();
                    fragmentTransaction.add(R.id.container, categoriesListFragment);
                    fragmentTransaction.commit();
                    return true;
                case R.id.navigation_bookings:
//                    mTextMessage.setText(R.string.title_bookings);
                    return true;
                case R.id.navigation_chats:
//                    mTextMessage.setText(R.string.title_chats);
                    return true;
                case R.id.navigation_settings:
                    return true;

            }
            return false;
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);


        BottomNavigationView navigation = findViewById(R.id.navigation);
        navigation.setOnNavigationItemSelectedListener(mOnNavigationItemSelectedListener);

        fragmentManager = getSupportFragmentManager();
        fragmentTransaction = fragmentManager.beginTransaction();
    }


    @Override
    public void onCategorySelected(String category) {
        Log.w(TAG, "Successfully created CategoryListFragment!");
    }
}

layout_main layout

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/container"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".view.main.MainActivity">


    <android.support.design.widget.BottomNavigationView
        android:id="@+id/navigation"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_marginEnd="0dp"
        android:layout_marginStart="0dp"
        android:background="?android:attr/windowBackground"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:menu="@menu/navigation" />




</android.support.constraint.ConstraintLayout>

Fragment

package com.alsowaygh.getitdone.view.services;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;

import com.alsowaygh.getitdone.R;
import com.alsowaygh.getitdone.view.main.MainActivity;

public class CategoriesListFragment extends Fragment {
    private ListView categoriesListView;
    OnCategorySelectedListener categoryListener;



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

        //initializing root view first to refer to it
        View rootView = inflater.inflate(R.layout.activity_main, container, false);

        //initializing ListView
        categoriesListView = getView().findViewById(R.id.categoriesList);

        //categories list
        final String[] categories = {"first category", "second category", "third category", "Fourth category"};

        //initializing and adding categories strings to the addapter
        ArrayAdapter<String> arrayAdapter = new ArrayAdapter<>(this.getContext(),
                R.layout.category_textview);
        for (String c : categories) {
            arrayAdapter.add(c);
        }
        categoriesListView.setAdapter(arrayAdapter);

        //implement onListItemClick
        categoriesListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                //retrieve string from categories list at clicked position
            categoryListener.onCategorySelected(categories[position]);
            }
        });

        return rootView;
    }

    @Override //to fource container activity to implement the OnCategorySelectedListener
    public void onAttach(Context context) {
        super.onAttach(context);
        try{
            categoryListener  = (OnCategorySelectedListener) context;
        }catch(ClassCastException e){
            throw new ClassCastException(context.toString() + "must implement OnCategorySelectedListener");
        }
    }


}

контейнер фрагментов

<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/fragment_container"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <fragment
        android:id="@+id/categories_list_fragment"
        android:name="com.alsowaygh.getitdone.view.services.CategoriesListFragment"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_marginBottom="8dp"
        android:layout_marginTop="8dp">

        <ListView
            android:id="@+id/categoriesList"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_marginBottom="8dp"
            android:layout_marginEnd="8dp"
            android:layout_marginLeft="8dp"
            android:layout_marginRight="8dp"
            android:layout_marginStart="8dp"
            android:layout_marginTop="8dp" />

    </fragment>
</FrameLayout>

Ваша помощь будет высоко оценена.

1 Ответ

0 голосов
/ 04 июня 2018

Вам необходимо добавить контейнер FrameLayout в файл макета MainActivity (activity_main), щелкнув по кнопке в BottomNavigationView, заменить ее фрагментом.Таким образом, у вас есть действие, и фрагменты отображаются внутри действия, при щелчке каждого элемента меню вы можете вызвать его, чтобы заменить его фрагментами.Это должно решить вашу проблему.

Вам необходимо изменить макет, как показано ниже в файле activity_main.xml.

<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/container"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".view.main.MainActivity">

          <FrameLayout
            android:id="@+id/frame"
            android:layout_width="match_parent"
            android:layout_height="match_parent" />

    <android.support.design.widget.BottomNavigationView
        android:id="@+id/navigation"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginEnd="0dp"
        android:layout_marginStart="0dp"
        android:background="?android:attr/windowBackground"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:menu="@menu/navigation" />
</android.support.constraint.ConstraintLayout>

В коде MainActivity необходимо изменить, как показано ниже:

case R.id.navigation_services:
//                    mTextMessage.setText(R.string.title_services);
                    CategoriesListFragment categoriesListFragment = new CategoriesListFragment();
                    fragmentTransaction.replace(R.id.frame, categoriesListFragment);
                    fragmentTransaction.commit();
                    return true;

В файле макета фрагмента измените на LinearLayout:

<LinearLayout
    android:id="@+id/categories_list_fragment"
 android:name="com.alsowaygh.getitdone.view.services.CategoriesListFragment"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_marginBottom="8dp"
    android:layout_marginTop="8dp">

    <ListView
        android:id="@+id/categoriesList"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_marginBottom="8dp"
        android:layout_marginEnd="8dp"
        android:layout_marginLeft="8dp"
        android:layout_marginRight="8dp"
        android:layout_marginStart="8dp"
        android:layout_marginTop="8dp" />

</LinearLayout>

РЕДАКТИРОВАТЬ

Вфрагмент кода, измените макет на имя файла макета фрагмента (R.layout.fragment_layout_name).

View rootView = inflater.inflate(R.layout.fragment_layout_name, container, false);
    //initializing ListView
categoriesListView = rootView.findViewById(R.id.categoriesList);
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...