Используйте метод / функцию из другого фрагмента - PullRequest
0 голосов
/ 11 октября 2018

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

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

Итак, MainActivity> MainFragment> (Fragment1, Fragment2и т.д.).

То, что я всегда вижу, это MainActivity> (Fragment1, Fragment2).

Так что мой метод переключения находится внутри MainFragment, и Fragment1,2 будет использовать его для замены.

и я не могу этого сделать.Я пытался использовать этот код, но он не работает,

bookingFragment = (BookingFragment) getFragmentManager().findFragmentById(R.id.fragment_booking);

и в ответе об ошибке все время говорится, что я пытаюсь прочитать нулевой объект.

Main:

<android.support.v4.widget.DrawerLayout
    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:layout_width="match_parent"
    android:layout_height="match_parent"
    android:id="@+id/drawer_layout"
    tools:context=".Modules.Activities.MainActivity">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:background="@color/bg_tan"
        android:orientation="vertical">

        <android.support.v7.widget.Toolbar
            android:id="@+id/toolbar"
            android:layout_width="match_parent"
            android:layout_height="?attr/actionBarSize"
            android:background="?attr/colorPrimary"
            android:elevation="4dp"
            android:theme="@style/ThemeOverlay.AppCompat.ActionBar"
            app:popupTheme="@style/ThemeOverlay.AppCompat.Light">

            <ImageView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_margin="5dp"
                android:layout_gravity="center"
                android:src="@drawable/img_logo_header"/>
        </android.support.v7.widget.Toolbar>

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

    </LinearLayout>

    <android.support.design.widget.NavigationView
        android:id="@+id/nav_view"
        android:layout_width="wrap_content"
        android:layout_height="match_parent"
        android:layout_gravity="start"
        android:fitsSystemWindows="true"
        android:background="#FFF"
        app:menu="@menu/drawer_view"
        app:headerLayout="@layout/nav_header"  />

</android.support.v4.widget.DrawerLayout>

Первый фрагмент:

<LinearLayout 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/fragment_booking"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@color/bg_tan"
    android:orientation="vertical"
    tools:context=".Modules.Fragments.BookingFragment">

    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent">

        <LinearLayout
            android:id="@+id/layout_status"
            android:layout_marginTop="3dp"
            android:layout_alignParentTop="true"
            android:layout_width="match_parent"
            android:layout_height="wrap_content">
            <ImageView
                android:id="@+id/iv_book_status_address"
                android:layout_weight="1"
                android:background="@drawable/one_orange"
                android:layout_width="0dip"
                android:layout_height="wrap_content" />
            <ImageView
                android:id="@+id/iv_book_status_recipient"
                android:layout_weight="1"
                android:background="@drawable/two_gray"
                android:layout_width="0dip"
                android:layout_height="wrap_content" />
            <ImageView
                android:id="@+id/iv_book_status_package"
                android:layout_weight="1"
                android:background="@drawable/three_gray"
                android:layout_width="0dip"
                android:layout_height="wrap_content" />
        </LinearLayout>

        <LinearLayout
            android:layout_marginTop="3dp"
            android:layout_alignParentTop="true"
            android:layout_width="match_parent"
            android:layout_height="wrap_content">
            <TextView
                android:id="@+id/tv_book_status_address"
                android:layout_weight="1"
                android:layout_width="0dip"
                android:layout_height="wrap_content"
                android:gravity="center_horizontal"
                android:paddingVertical="@dimen/_5sdp"
                android:text="Address"
                android:textColor="@color/colorPrimaryDark"/>
            <TextView
                android:id="@+id/tv_book_status_recipient"
                android:layout_weight="1"
                android:layout_width="0dip"
                android:layout_height="wrap_content"
                android:gravity="center_horizontal"
                android:paddingVertical="@dimen/_5sdp"
                android:text="Recipient"
                android:textColor="@color/hint"/>
            <TextView
                android:id="@+id/tv_book_status_package"
                android:layout_weight="1"
                android:layout_width="0dip"
                android:layout_height="wrap_content"
                android:gravity="center_horizontal"
                android:paddingVertical="@dimen/_5sdp"
                android:text="Packaging"
                android:textColor="@color/hint"/>
        </LinearLayout>

        <FrameLayout
            android:layout_below="@id/layout_status"
            android:id="@id/container"
            android:layout_width="match_parent"
            android:layout_height="fill_parent"/>

    </RelativeLayout>
</LinearLayout>

Фрагмент2:

<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:map="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@color/bg_tan"
    tools:context=".Modules.Fragments.BookAddressFragment">
    <fragment
        android:id="@+id/map_address"
        android:name="com.google.android.gms.maps.SupportMapFragment"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        map:cameraZoom="17"/>

    <LinearLayout
        android:layout_above="@id/layout_address"
        android:layout_width="match_parent"
        android:layout_height="@dimen/_35sdp">

        <Button
            android:id="@+id/btn_on_demand"
            android:layout_marginHorizontal="@dimen/_5sdp"
            android:background="@drawable/btn_white"
            android:elevation="10dp"
            android:layout_weight="1"
            android:layout_width="0dip"
            android:layout_height="@dimen/_30sdp"
            android:text="On Demand"
            android:textColor="@color/hint"
            android:textAllCaps="false"/>

        <Button
            android:id="@+id/btn_next_day"
            android:layout_marginHorizontal="@dimen/_5sdp"
            android:background="@drawable/btn_white"
            android:elevation="10dp"
            android:layout_weight="1"
            android:layout_width="0dip"
            android:layout_height="@dimen/_30sdp"
            android:text="Next Day"
            android:textColor="@color/hint"
            android:textAllCaps="false"/>

        <Button
            android:id="@+id/btn_2_3_days"
            android:layout_marginHorizontal="@dimen/_5sdp"
            android:background="@drawable/btn_white"
            android:elevation="10dp"
            android:layout_weight="1"
            android:layout_width="0dip"
            android:layout_height="@dimen/_30sdp"
            android:text="2-3 Days"
            android:textColor="@color/hint"
            android:textAllCaps="false"/>
    </LinearLayout>

    <LinearLayout
        android:id="@+id/layout_address"
        android:background="@drawable/btn_white"
        android:layout_alignParentBottom="true"
        android:layout_margin="@dimen/_5sdp"
        android:elevation="10dp"
        android:orientation="vertical"
        android:layout_width="match_parent"
        android:layout_height="wrap_content">

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_margin="@dimen/_5sdp"
            android:text="Single Booking"
            android:textColor="@color/hint"/>

        <LinearLayout
            android:gravity="center_vertical"
            android:layout_marginHorizontal="@dimen/_5sdp"
            android:layout_width="match_parent"
            android:layout_height="wrap_content">
            <ImageView
                android:layout_margin="@dimen/_5sdp"
                android:background="@drawable/ic_circle_pickup_small"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content" />

            <EditText
                android:id="@+id/et_book_address_pickup"
                android:background="@drawable/border_round_gray"
                android:layout_width="match_parent"
                android:layout_height="@dimen/_35sdp"
                android:layout_marginVertical="@dimen/_5sdp"
                android:paddingHorizontal="@dimen/_10sdp"
                android:textColorHint="@color/hint"
                android:textColor="@color/blitz_gray"
                android:inputType="text"
                android:hint="Pick up at"
                android:singleLine="true" />
        </LinearLayout>

        <LinearLayout
            android:gravity="center_vertical"
            android:layout_marginHorizontal="@dimen/_5sdp"
            android:layout_width="match_parent"
            android:layout_height="wrap_content">
            <ImageView
                android:layout_margin="@dimen/_5sdp"
                android:background="@drawable/ic_circle_deliver_small"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content" />

            <EditText
                android:id="@+id/et_book_address_deliver"
                android:background="@drawable/border_round_gray"
                android:layout_width="match_parent"
                android:layout_height="@dimen/_35sdp"
                android:layout_marginVertical="@dimen/_5sdp"
                android:paddingHorizontal="@dimen/_10sdp"
                android:textColorHint="@color/hint"
                android:textColor="@color/blitz_gray"
                android:inputType="text"
                android:hint="Deliver to"
                android:singleLine="true" />
        </LinearLayout>

        <Button
            android:id="@+id/btn_book_address"
            android:layout_width="match_parent"
            android:layout_height="@dimen/_35sdp"
            android:background="@color/blitz_yellow"
            android:text="Enter recipient details"
            android:textAllCaps="false"
            android:textSize="16sp"
            android:textColor="#000" />
    </LinearLayout>
</RelativeLayout>

Ответы [ 4 ]

0 голосов
/ 11 октября 2018

Ваши фрагменты не должны взаимодействовать друг с другом напрямую, это не рекомендуется.вместо этого они должны общаться через посредника, в этом случае ваша деятельность будет:

, так что здесь вам нужно сделать - создать интерфейс

    public interface Communicator {

    public void switchFragments();
}

- теперь ваша деятельность должна реализовать этот интерфейс ипереопределить метод switchFragments ()

  • Теперь создайте экземпляр интерфейса Communicator во фрагменте, который должен вызывать для изменения фрагмента, а затем переопределите onAttach во фрагменте и назначьте так:

    коммуникатор коммуникатор;@Override public void onAttach (Context context) {super.onAttach (context);

    try {
        communicator = (YourActivity) context;
    }catch (ClassCastException cce){
        cce.printStackTrace();
    }
    

    } теперь всякий раз, когда вам нужно позвонить, чтобы изменить фрагмент:

    communator.switchFragments ();

внутри вашей деятельности вы можете вызывать метод внутри вашего первого фрагмента и делать то, что вам нужно.

0 голосов
/ 11 октября 2018

// в вашем фрагменте

public void callFunction(){

}

// в другом фрагменте

MyClassName obj=new MyClassName();
obj.callFunction()
0 голосов
/ 11 октября 2018

Наиболее эффективным способом было бы использование BroadcastReceiver, в вашем первом фрагменте создайте получатель

public class CustomBroadcastReceiver extends BroadcastReceiver {
 @Override
    OnReceive(Intent intent){
     // do what you need to do
    }
}

IntentFilter filter = new IntentFilter(“filter”);
CustomerBroadcastReceiver receiver = new BroadcastReceiver();

Зарегистрируйте его

LocalBroadcastReceiver.getInstance(this).registerReceiver(receiver, filter);

Во фрагменте 2, когда вы хотите активировать еговсе, что вам нужно сделать, это

LocalBroadcastReceiver.getInstance(this).sendBroadcast(new Intent);
0 голосов
/ 11 октября 2018

Когда вы переходите на второй фрагмент, я полагаю, вы делаете замену вместо добавление в транзакции.При вызове замены существующий фрагмент будет находиться в backstack и, следовательно, все методы и переменные будут уничтожены.Поэтому, когда вы вызываете метод, объявленный в Frag1 из Frag2 , то, поскольку Frag1 больше не существует в памяти, он наверняка вернет исключение нулевого указателя.

Если вы хотите использовать эту функцию слишком много в разных фрагментах, попробуйте реорганизовать ее в класс активности, а затем используйте ее, вызвав

getActivity().method_name();
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...