Как убрать пустое место, когда видимость установлена ​​на GONE - PullRequest
0 голосов
/ 23 марта 2020

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

Я пытался поставить layout_height как wrap_content, но он все равно ничего не показывает.

Recycler View :

<?xml version="1.0" encoding="utf-8"?>
    <androidx.constraintlayout.widget.ConstraintLayout
        xmlns:tools="http://schemas.android.com/tools"
        xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="match_parent"
        android:layout_height="match_parent">

        <androidx.recyclerview.widget.RecyclerView
            android:id="@+id/recycleView"
            android:layout_gravity="top"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            tools:layout_editor_absoluteX="1dp"
            tools:layout_editor_absoluteY="1dp" />

    </androidx.constraintlayout.widget.ConstraintLayout> 

Просмотр карты:

<?xml version="1.0" encoding="utf-8"?>
<androidx.cardview.widget.CardView 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="250dp"
    android:layout_marginLeft="10dp"
    android:layout_marginTop="10dp"
    android:layout_marginRight="10dp"
    android:id="@+id/cardView"
    android:backgroundTint="#5A10E7"
    android:elevation="90dp"
    android:orientation="vertical"
    android:textColor="#FFFFFF"
    app:cardCornerRadius="25dp"
    app:layout_constraintBottom_toBottomOf="parent"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintHorizontal_bias="0.5"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toTopOf="parent"
    app:layout_constraintVertical_bias="0.282">

    <androidx.constraintlayout.widget.ConstraintLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent">

        <Button
            android:id="@+id/Requestfulfilled"
            android:layout_width="139dp"
            android:layout_height="41dp"
            android:layout_weight="1"
            android:backgroundTint="#4CAF50"
            android:clickable="true"
            android:defaultFocusHighlightEnabled="true"
            android:hint="Request Fullfilled"
            android:text="Fulfilled"
            android:textColor="#FFFFFF"
            app:layout_constraintBottom_toBottomOf="parent"
            app:layout_constraintEnd_toStartOf="@+id/DeleteRequest"
            app:layout_constraintHorizontal_bias="0.5"
            app:layout_constraintStart_toStartOf="@+id/RlocationView"
            app:layout_constraintTop_toBottomOf="@+id/RlocationView" />

        <Button
            android:id="@+id/DeleteRequest"
            android:layout_width="139dp"
            android:layout_height="41dp"
            android:backgroundTint="#F44336"
            android:clickable="true"
            android:defaultFocusHighlightEnabled="true"
            android:hint="Delete"
            android:text="Delete"
            android:textColor="#FFFFFF"
            app:layout_constraintBottom_toBottomOf="parent"
            app:layout_constraintEnd_toEndOf="@+id/RlocationView"
            app:layout_constraintHorizontal_bias="0.894"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toTopOf="parent"
            app:layout_constraintVertical_bias="0.904" />

        <TextView
            android:id="@+id/RemailView"
            android:layout_width="340dp"
            android:layout_height="35dp"
            android:allowUndo="true"
            android:focusable="auto"
            android:focusableInTouchMode="true"
            android:text="Email"
            android:textAlignment="center"
            android:textColor="#FFFFFF"
            android:textSize="18sp"
            app:layout_constraintBottom_toTopOf="@+id/RdateView"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintHorizontal_bias="0.5"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toTopOf="parent" />

        <TextView
            android:id="@+id/RbloodView"
            android:layout_width="116dp"
            android:layout_height="35dp"
            android:allowUndo="true"
            android:focusable="auto"
            android:focusableInTouchMode="true"
            android:text="Blood Group"
            android:textAlignment="center"
            android:textColor="#FFFFFF"
            android:textSize="18sp"
            app:layout_constraintBottom_toTopOf="@+id/RlocationView"
            app:layout_constraintEnd_toStartOf="@+id/RdateView"
            app:layout_constraintHorizontal_bias="0.5"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toBottomOf="@+id/RemailView" />

        <TextView
            android:id="@+id/RdateView"
            android:layout_width="164dp"
            android:layout_height="42dp"
            android:allowUndo="true"
            android:focusable="auto"
            android:focusableInTouchMode="true"
            android:text="Date of Requirement"
            android:textAlignment="center"
            android:textColor="#FFFFFF"
            android:textSize="18sp"
            app:layout_constraintBottom_toTopOf="@+id/RlocationView"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintHorizontal_bias="0.5"
            app:layout_constraintStart_toEndOf="@+id/RbloodView"
            app:layout_constraintTop_toBottomOf="@+id/RemailView" />

        <TextView
            android:id="@+id/RlocationView"
            android:layout_width="340dp"
            android:layout_height="35dp"
            android:allowUndo="true"
            android:focusable="auto"
            android:focusableInTouchMode="true"
            android:text="Location"
            android:textAlignment="center"
            android:textColor="#FFFFFF"
            android:textSize="18sp"
            app:layout_constraintBottom_toTopOf="@+id/Requestfulfilled"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintHorizontal_bias="0.5"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toBottomOf="@+id/RdateView" />

    </androidx.constraintlayout.widget.ConstraintLayout>

</androidx.cardview.widget.CardView>

Код для установки видимости карты как GONE:

   public class yourRequestActivity extends AppCompatActivity {

    private RecyclerView cardView;

    private DatabaseReference dbRefForReq, dbRefForResp;

    private FirebaseAuth mAuth;

    private String AuthUserEmail, UserID;

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

        mAuth = FirebaseAuth.getInstance();

        AuthUserEmail = mAuth.getCurrentUser().getEmail();

        UserID = mAuth.getCurrentUser().getUid();

        dbRefForResp = FirebaseDatabase.getInstance().getReference().child("Responses").child(String.valueOf(UserID));

        dbRefForReq = FirebaseDatabase.getInstance().getReference().child("Blood Requests");
        dbRefForReq.keepSynced(true);

        cardView = (RecyclerView) findViewById(R.id.recycleView);
        cardView.setHasFixedSize(true);
        cardView.setLayoutManager(new LinearLayoutManager(this));

    }

    @Override
    protected void onStart() {
        super.onStart();
        FirebaseRecyclerOptions<getDbContents> options =
                new FirebaseRecyclerOptions.Builder<getDbContents>()
                        .setQuery(dbRefForReq, getDbContents.class)
                        .build();

        FirebaseRecyclerAdapter<getDbContents, contentHolder> adapter = new FirebaseRecyclerAdapter<getDbContents, contentHolder>(options) {
            @Override
            protected void onBindViewHolder(@NonNull final contentHolder holder, final int position, @NonNull final getDbContents model) {
                final int finalPosition = position + 1;
                if (model.getUser().equals(AuthUserEmail)) {
                    dbRefForReq.addValueEventListener(new ValueEventListener() {
                        @Override
                        public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
                            DataSnapshot checkFulfillment = dataSnapshot.child(String.valueOf(("Request " + finalPosition))).child("Fulfillment");
                            if (checkFulfillment.exists()) {
                                if (checkFulfillment.child("Fulfilled").getValue().equals("yes")) {
                                    /*------------- Set current user card as visible -----------------*/
                                    holder.frameView.setVisibility(View.VISIBLE);
                                    holder.fulfilled.setVisibility(View.GONE);
                                    holder.requestFulfilled.setVisibility(View.VISIBLE);
                                    holder.userEmail.setText(AuthUserEmail);
                                    holder.bloodGroup.setText(model.getBloodGroup());
                                    holder.dateOfRequirement.setText(model.getDate());
                                    holder.Location.setText(model.getLocation());
                                    ////////////////////////////////////////////////////////////////////
                                }
                            } else {
                                holder.frameView.setVisibility(View.VISIBLE);
                                holder.fulfilled.setVisibility(View.VISIBLE);
                                holder.requestFulfilled.setVisibility(View.GONE);
                                /*------------- Set current user card as visible -----------------*/
                                holder.userEmail.setText(AuthUserEmail);
                                holder.bloodGroup.setText(model.getBloodGroup());
                                holder.dateOfRequirement.setText(model.getDate());
                                holder.Location.setText(model.getLocation());
                                ////////////////////////////////////////////////////////////////////
                            }

                        }
                        @Override
                        public void onCancelled(@NonNull DatabaseError databaseError) {

                        }
                    });

                } else if (model.getUser().equals(null)) {
                    holder.userEmail.setText("You have not posted any request");
                } else {
                    holder.frameView.setVisibility(View.GONE);
                }

                /*  Fulfilled and Delete button Functionality  */
                holder.fulfilled.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        Map<String, Object> response = new HashMap<>();
                        response.put("Fulfilled", "yes");

                        /*-----------------Remove Responses------------------*/

                        dbRefForResp.removeValue();
                        ///////////////////////////////////////////////////////

                        /*-----------------Update and insert child with fulfilled status as yes------------------*/
                        dbRefForReq.child(String.valueOf(("Request " + finalPosition))).child("Fulfillment").setValue(response).addOnSuccessListener(new OnSuccessListener<Void>() {
                            @Override
                            public void onSuccess(Void aVoid) {
                                Toast.makeText(yourRequestActivity.this, "Request fulfillment status posted", Toast.LENGTH_SHORT).show();
                            }
                        });
                        ////////////////////////////////////////////////////////////////////
                        holder.fulfilled.setVisibility(View.GONE);
                        holder.requestFulfilled.setVisibility(View.VISIBLE);
                    }
                });

            }

            @NonNull
            @Override
            public contentHolder onCreateViewHolder(@NonNull ViewGroup viewGroup, int viewType) {
                View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.your_request_card, viewGroup, false);
                contentHolder contentViewHolder = new contentHolder(view);
                return contentViewHolder;
            }
        };
        cardView.setAdapter(adapter);
        adapter.startListening();

    }


    public class contentHolder extends RecyclerView.ViewHolder {
        TextView userEmail, bloodGroup, dateOfRequirement, Location, requestFulfilled;
        Button fulfilled;
        FrameLayout frameView;

        public contentHolder(@NonNull View itemView) {
            super(itemView);
            userEmail = itemView.findViewById(R.id.RemailView);
            bloodGroup = itemView.findViewById(R.id.RbloodView);
            dateOfRequirement = itemView.findViewById(R.id.RdateView);
            Location = itemView.findViewById(R.id.RlocationView);

            requestFulfilled = (TextView) itemView.findViewById(R.id.fulfilledTextMessage);
            frameView = (FrameLayout) itemView.findViewById(R.id.cardFrame);
            fulfilled = (Button) itemView.findViewById(R.id.Requestfulfilled);
        }
    }
}

Я хочу удалить пустое пространство, которое появляется, когда видимость установлена ​​на GONE, как показано на снимке ниже.

Изображение пустого пространства при удалении верхней карты

Изображение перед настройкой видимости GONE

Ответы [ 3 ]

0 голосов
/ 23 марта 2020

Накройте свой RecyclerView с помощью FrameLayout, а затем установите там свою видимость.

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
    xmlns:tools="http://schemas.android.com/tools"
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <FrameLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:visibility="gone">

    <androidx.recyclerview.widget.RecyclerView
        android:id="@+id/recycleView"
        android:layout_gravity="top"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        tools:layout_editor_absoluteX="1dp"
        tools:layout_editor_absoluteY="1dp" />

    </FrameLayout>
</androidx.constraintlayout.widget.ConstraintLayout> 

Если это не сработает, то:

Покройте ваш Cardview, который является макетом, который вы разработали для своего Recyclerview с FrameLayout. Любой из них обязательно сработает для вас.

0 голосов
/ 23 марта 2020

Просто удалите объект из списка, если его пользователь не равен AuthUserEmail, и сообщите об этом вашему адаптеру.

НЕТ НЕОБХОДИМОСТИ, ЧТОБЫ ПОЛУЧИТЬ ВИДИМОСТЬ ВИДА ДЕРЖАТЕЛЯ

0 голосов
/ 23 марта 2020

Ваш RecyclerView занимает место, даже если видимость отключена. Это все еще занимает место, потому что есть элементы, которые RecyclerView хочет отобразить. Хотя это можно исправить, удалив элементы, которые RecyclerView хочет показать. Потребуется много памяти, если вы захотите снова показать это RecyclerView, потому что вам все равно придется добавлять элементы обратно. Я бы порекомендовал обернуть ваш RecyclerView макетом, например. LinearLayout и установите видимость этого макета как пропавшую.

Попробуйте сделать это:

<LinearLayout
    android:id="@+id/container"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical">

    <!--  Place your RecyclerView here -->
    <!--  change visibility of container view -->

</LinearLayout>

* Редактировать: Вы плохо объяснили. Я получаю то, что вы хотите сейчас. Вам просто нужно удалить предмет из списка RecyclerView. Лучший способ сделать это - использовать DiffUtil. Это отличный онлайн-учебник, показывающий, как вы можете реализовать его в Java. https://codinginflow.com/tutorials/android/room-viewmodel-livedata-recyclerview-mvvm/part-1-introduction

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