Кнопка Android не активируется при повороте - PullRequest
0 голосов
/ 26 апреля 2020

Привет, я публикую это после того, как не могу найти здесь никакого возможного ответа.

У меня есть невидимый LinearLayout LL1 во фрагменте, который я становлюсь видимым, когда данные recylerView пусты, что на LL1 есть кнопка. Проблема в том, что кнопка не кликабельна! Я пытался настроить слушателя по-разному, но все еще не работал. Вот код ниже:

Вот файл xml:

 <android.support.design.widget.CoordinatorLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".activity.main.MainActivity"
    android:layout_marginTop="3dp">

    <LinearLayout
        android:id="@+id/msg_emty_layout"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:gravity="center"
        android:visibility="gone"
        android:orientation="vertical">

        <ImageView
            android:layout_width="100dp"
            android:layout_height="100dp"
            android:src="@drawable/ic_empty_box" />
        <TextView
            android:layout_marginTop="10dp"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Aucune vente n'a été trouvée !"
            android:textSize="15dp"
            android:layout_gravity="center_horizontal"
            android:textColor="@color/greydark"/>
        <Button
            android:id="@+id/btnAddSale"
            android:layout_marginTop="5dp"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Créer une vente"
            android:textColor="@color/whiteTextColor"
            android:background="@drawable/centre_button">

        </Button>

    </LinearLayout>

    <android.support.v4.widget.SwipeRefreshLayout
        android:id="@+id/swipe_refresh_db"
        android:layout_width="match_parent"
        android:layout_height="wrap_content">

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

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

    <android.support.design.widget.FloatingActionButton
        android:id="@+id/fab_add_db"
        android:layout_margin="20dp"
        android:layout_gravity="bottom|end"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:background="@color/colorAccesGreen"
        android:src="@drawable/ic_edit"/>


</android.support.design.widget.CoordinatorLayout>

А вот java:

   private void generateSaleList(ArrayList<Sale> saleArrayList, View view) {
    if(saleArrayList.isEmpty()){
        getActivity().setTitle("Ventes sur portable");
        msgLayout.setVisibility(View.VISIBLE);
        creatSaleBtn = (Button) view.findViewById(R.id.btnAddSale);
        creatSaleBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Toast.makeText(getActivity(), "Button clicked !", Toast.LENGTH_LONG).show();
            }
        });
        creatSaleBtn.setClickable(true);

    }else{
        msgLayout.setVisibility(View.GONE);
        recyclerView_db = view.findViewById(R.id.recycler_view_sale_list);
        adapter_db = new SaleAdapter((ArrayList<Sale>) Utils.sortArray(saleArrayList),this,1,getContext(),this);
        RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(getActivity());
        recyclerView_db.setLayoutManager(layoutManager);
        recyclerView_db.setAdapter(adapter_db);
        adapter_db.notifyDataSetChanged();
    }

}

Ребята, вы видите, что вызывает это странная проблема?

Ответы [ 4 ]

1 голос
/ 26 апреля 2020

Вы можете попробовать с requestFocusFromTouch()

Позвоните, чтобы попытаться сфокусировать внимание на конкретном c виде или на одном из его потомки.

 msgLayout.setVisibility(View.VISIBLE);
 creatSaleBtn = (Button) view.findViewById(R.id.btnAddSale);
 creatSaleBtn.requestFocusFromTouch();
0 голосов
/ 26 апреля 2020

как вы сказали в комментариях, вы нигде не используете creatSaleBtn.setClickable(false);, тогда вам нужно скрыть recyclerView, используя recyclerView_db.setVisibility(View.GONE);

почему? потому что по умолчанию он подходит для полноэкранного режима из-за match_parent для ширины и высоты.

, пожалуйста, добавьте recyclerView_db.setVisibility(View.GONE); в saleArrayList.isEmpty() check

, чтобы ваш новый код был:

if(saleArrayList.isEmpty()){
    recyclerView_db.setVisibility(View.GONE);
    getActivity().setTitle("Ventes sur portable");
    msgLayout.setVisibility(View.VISIBLE);
    creatSaleBtn = (Button) view.findViewById(R.id.btnAddSale);
    creatSaleBtn.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Toast.makeText(getActivity(), "Button clicked !", Toast.LENGTH_LONG).show();
        }
    });
    creatSaleBtn.setClickable(true);

}
0 голосов
/ 26 апреля 2020

Скрыть свой RecyclerView, когда нет элементов (установите видимость исчезла). Проблема в том, что он захватывает клики, так как он находится сверху кнопки.

0 голосов
/ 26 апреля 2020

Видимость SwipeRefreshLayout должна быть УТОЧНЕНА после того, как в режиме recyclerview пусто.
из грубого recyclcerview пусто, но все еще видимо, поэтому события щелчка перехватываются SwipeRefreshLayout, который определен поверх LL1.
РЕДАКТИРОВАТЬ
вместо просмотра повторного просмотра установите видимость swipe_refresh_db в состояние «пропало», так как я сомневаюсь, что просмотрщик рефералов является дочерним элементом swipe_refresh_dd, поэтому, если вы задаете видимость в панели восстановления, пропущенный swipe_refresh_db по-прежнему отображается и получает события нажатия.
попробуй

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