Tôi có một danh sách các bài đăng và hầu hết trong số đó là ảnh (chỉ cần đặt nó là các bài đăng giống như ứng dụng G + hoặc FB). Mỗi bài đăng có tỷ lệ cỡ ảnh, vì vậy tôi có thể đặt chiều cao hình ảnh dựa trên chiều rộng của ảnh ngay cả trước khi hình ảnh được tải từ máy chủ, do đó bố cục thẻ sẽ không thay đổi khi tải.Nhận chiều rộng của CardView trong Adapter.onBindViewHolder
Sự cố là layout_width="match_parent"
đặt cho cả thẻ và hình ảnh bài đăng. Khi tôi nhận được chiều rộng của cardview nó là số không. Vì vậy, tôi không thể tính toán chiều cao.
Hiện tại, giải pháp duy nhất tôi thấy là lấy chiều rộng của vùng chứa mẹ (RecyclerView) và khấu trừ tất cả các phần đệm, nhưng nó không giống như một giải pháp tốt.
Có cách nào khác để làm điều đó không?
Dưới đây là một ví dụ về mã bộ chuyển đổi
@Override
public void onBindViewHolder(ViewHolder holder, int position) {
....
int width = holder.itemView.getWidth();
....
//do some calculations
}
Layouts (không có phần không liên quan)
<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:card_view="http://schemas.android.com/apk/res-auto"
android:id="@+id/card"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:descendantFocusability="blocksDescendants"
android:foreground="?android:attr/selectableItemBackground"
card_view:cardBackgroundColor="#ffffff"
card_view:cardCornerRadius="3dp">
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<include
android:id="@+id/includedPost"
layout="@layout/post_details" />
</RelativeLayout>
</android.support.v7.widget.CardView>
includedPost:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<ImageView
android:id="@+id/postImage"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="@+id/commenterImage"
android:minHeight="120dp"
android:scaleType="centerCrop" />
</RelativeLayout>
Bạn có thể đặt một phần mã nơi bạn gọi phương thức getWidth (với kết quả 0) không? –
Cập nhật câu hỏi của tôi với mã mẫu – Andrew
Có thể bạn có thể thử gọi phương thức getWidth() trong [onViewAttachedToWindow] (https://developer.android.com/reference/android/support/v7/widget/RecyclerView.Adapter.html#onViewAttachedToWindow (VH)) theo tài liệu: "Điều này có thể được sử dụng như là một tín hiệu hợp lý mà quan điểm sắp được nhìn thấy bởi người dùng" –