Как сделать дочерний фрагмент обновленным из его родительского фрагмента - PullRequest
0 голосов
/ 08 июня 2018

Здравствуйте, у меня есть фрагмент и внутри него видоискатель с 2 вкладками, который мне нужен, когда я нажимаю кнопку в родительском фрагменте, обновляю дочерний фрагмент на странице просмотра. Я использовал это для обновления того же фрагмента, и он работает нормально

        FragmentTransaction ft1 = getFragmentManager().beginTransaction();
        ft1.detach(this).attach(this).commit();

Я попробовал то же самое, и вместо этого я положил childfragment.newInstance (), который все еще не обновлен, поэтому любое предложение ??

1 Ответ

0 голосов
/ 08 июня 2018
  1. Создайте интерфейс в вашем дочернем фрагменте.RefreshInterface

  2. создать метод в дочернем фрагменте для назначения объекта RefreshInterface.intialiseRefreshInterface (RefreshInterface refreshInterface)

  3. вызывает метод интерфейса внутри щелчка обновления.

  4. реализует дочерний фрагмент интерфейса в родительском фрагменте и переопределяет метод.

  5. до commit () дочерний фрагмент из родительского фрагмента 1. создать объект для дочернего объекта 2. вызвать intialiseRefreshInterface (RefreshInterface refreshInterface) 3. commit () дочерний фрагмент.

  6. ваш дочерний фрагмент будет обновлен [дочерний фрагмент будет popBackStack () и воссоздан.

Ниже приведен пример кодапоможет вам в достижении ваших требований

родительский фрагмент

parentFragment.java

    public class OneFragment extends Fragment implements TwoFragment.RefreshInterface {

    TwoFragment child;
    Button launch;
    FrameLayout containerLayout;
    // child fragment interface object
    TwoFragment.RefreshInterface refreshInterface;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_one, container, false);
        launch = view.findViewById(R.id.fragment_launch);
        containerLayout = view.findViewById(R.id.fragment_container);
        // RefreshInterface. this is mandatory
        refreshInterface = this;
        launch.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                launchChildFragment();
            }
        });
        return view;
    }

    @Override
    public void refresh_fragment() {
        // as we added the child fragment to backstack. we will remove the fragment from backstack and add again
        if (getActivity().getSupportFragmentManager().getBackStackEntryCount() > 0){
            getActivity().getSupportFragmentManager().popBackStack();
        }
        launchChildFragment();
    }

    private void launchChildFragment(){
        // creating the object for child fragment
        child = new TwoFragment();
        // intialising the RefreshInterface object
        child.intialiseRefreshInterface(refreshInterface);
        // calling the child fragment
        getActivity().getSupportFragmentManager().beginTransaction().add(R.id.fragment_container, child).addToBackStack(null).commit();
    }
}

frag_parent.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.myapplication.OneFragment">

    <Button
        android:layout_centerHorizontal="true"
        android:id="@+id/fragment_launch"
        android:text="Launch child fragment"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />
    <FrameLayout
        android:id="@+id/fragment_container"
        android:layout_below="@id/fragment_launch"
        android:layout_width="match_parent"
        android:layout_height="match_parent"/>

</RelativeLayout>

childFragment

public class TwoFragment extends Fragment {

    Button refershBtn;
    RefreshInterface refreshInterface;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_two, container, false);
        refershBtn = view.findViewById(R.id.btn_refersh);

        refershBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                refreshInterface.refresh_fragment();
            }
        });
        return view;
    }

    public void intialiseRefreshInterface(RefreshInterface refreshInterface){
        this.refreshInterface = refreshInterface;
    }

    public interface RefreshInterface {
        void refresh_fragment();
    }
}

фрагмент_членя.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.outthinking.myapplication.TwoFragment">

    <!-- TODO: Update blank fragment layout -->
    <EditText
        android:id="@+id/refersh_tv"
        android:textSize="24sp"
        android:textAlignment="center"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="REFRESH DATA" />

    <Button
        android:id="@+id/btn_refersh"
        android:text="refersh"
        android:layout_centerInParent="true"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />

</RelativeLayout>
...