Доступ к основной деятельности FloatingActionButton из фрагментов - PullRequest
0 голосов
/ 27 мая 2019

У меня есть активность с 3 фрагментами. Каждый фрагмент должен иметь FAB с различным значком действия. FAB определяется в основном макете деятельности. Теперь я увидел, что не могу получить к нему доступ из фрагментов. Как я могу это сделать?

Вот мой код: макет main_activity:

<?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:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <android.support.v4.view.ViewPager
        android:id="@+id/view_pager"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        app:layout_behavior="@string/appbar_scrolling_view_behavior"
        app:layout_constraintBottom_toTopOf="parent"
        app:layout_constraintTop_toBottomOf="parent"
        tools:layout_editor_absoluteX="16dp">


        <android.support.design.widget.TabLayout
            android:id="@+id/tabs"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            app:tabGravity="fill"
            app:tabMode="fixed" />
    </android.support.v4.view.ViewPager>


    <android.support.design.widget.FloatingActionButton
        android:id="@+id/fab"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_margin="24dp"
        android:src="@android:drawable/ic_dialog_email"
        android:visibility="visible"
        app:layout_constraintBottom_toTopOf="parent"
        app:layout_constraintEnd_toEndOf="parent" />

</android.support.constraint.ConstraintLayout>

макет моего фрагмента:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="horizontal" android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@color/colorBackgroundFragment">

    <android.support.v7.widget.RecyclerView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:id="@+id/contact_recycleview">

    </android.support.v7.widget.RecyclerView>

</LinearLayout>

раздувая фрагмент:

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    v= inflater.inflate(R.layout.filters_fragment,container,false);

    myrecyclerview = (RecyclerView) v.findViewById(R.id.contact_recycleview);
    recyclerAdapter = new RecyclerViewAdapterCall(getContext(), lstCall);
    myrecyclerview.setLayoutManager(new LinearLayoutManager((getActivity())));
    myrecyclerview.addItemDecoration(new DividerItemDecoration(getContext(), DividerItemDecoration.VERTICAL));
    myrecyclerview.setAdapter(recyclerAdapter);

    return v;
}

так что здесь я хотел бы изменить значок действия, как?

Ответы [ 4 ]

2 голосов
/ 27 мая 2019
Step 1 create interface
  public interface FabButtonClick {
         void onFabClicked();
void onFabClickedTwo()

    }

шаг 2: внутренняя деятельность

 FabButtonClick fabButtonClick ;

inside `oncreate()` of activity

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


switch(mViewPager.getCurrentItem()){
case 0: 
fabButtonClick.onFabClicked()
break;
case 1: 
fabButtonClick.onFabClickedTwo()
break;
etc
}

                }
            });

только внутри вида деятельности

private void setListener(FabButtonClick interface){
    fabButtonClick =interface;
}


fragment implement FabButtonClick 

внутренние фрагменты на ViewCreated

((YOUR_ACTIVITY_NAME)getActivity()).setListener(this)

переопределенный метод из интерфейса теперь позволяет обрабатывать потрясающие клики в Фрагмент

0 голосов
/ 27 мая 2019

Руководство разработчика Android рекомендует следующий способ связи Activity, Fragment.

Fragment доступ Activity слушателем. Activity доступ Fragment по getSupportFragmentManager().getFragments()

Итак, у вас есть два способа использования fab.

Во-первых, прямой доступ к fab в Fragment

class MyFragment extends Fragment {
    MyFragmentListener listener;

    void myFunction() {
        FloatingActionButton fab = listener.getFab();
        ...
    }
}

interface MyFragmentListener {
    FloatingActionButton getFab();
}

class MyActivity extends AppCompatActivity implements MyFragmentListener {
    FloationActionButton fab;

    @Override
    FloationActionButton getFab() {
        return fab;
    }

    @Override
    void onAttachFragment(Fragment fragment) {
        super.onAttachFragment(fragment);
        if(fragment instanceof MyFragment) {
            ((MyFragment) fragment).listener = this;
        }
    }
}

Во-вторых, вызов функции Fragment при нажатии fab

//In Activity
fab.setOnClickListener(new OnClickListener() {
    for(fragment : getSupportFragmentManager().getFragments()) {
        if(fragment instanceof MyFragment) {
            ((MyFragment) fragment).someFunction();
        }
    }
});
0 голосов
/ 27 мая 2019

Добавьте плавающие кнопки действий к вашим фрагментам. Добавьте его в макет фрагментов. Так будет проще и понятнее.

0 голосов
/ 27 мая 2019

Вызовите это из фрагмента

 Objects.requireNonNull(getActivity()).someOperationOnFab();

, где someOperationOnFab () определено в MainActivity

 public void someOperationOnFab(){
     yourFab. blah
}  
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...