我的布局中有一个水平的RecyclerView,其中填充了CustomImageView,确保在其中包含圆形drawable。当我添加这些自定义视图时,它们的宽度为零。此RecyclerView定义如下:
<android.support.v7.widget.RecyclerView
android:id="@+id/chart_months_list"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1.5"
android:backgroundTint="@color/saltpan"
/>
非常简单。参考我的CustomImageView,这是代码及其布局:
public class CustomImageView extends ImageView {
public CustomImageView(Context context) {
super(context);
}
public CustomImageView(Context context, AttributeSet attrs) {
super(context, attrs);
}
public CustomImageView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
Drawable d = getDrawable();
if (d != null) {
int w = MeasureSpec.getSize(widthMeasureSpec);
int h = w * d.getIntrinsicHeight() / d.getIntrinsicWidth();
double f1 = ((double)w)*0.78;
double f2 = ((double)h)*0.78;
setMeasuredDimension((int)f1, (int)f2);
Log.e("MEASURE", f1+" "+f2);
}
else super.onMeasure(widthMeasureSpec, heightMeasureSpec);
}
}
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/custom_cell"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@drawable/calendar_cell_bg"
android:gravity="center"
android:orientation="vertical"
android:paddingLeft="2.5dp"
android:paddingRight="2.5dp"
android:layout_margin="0dp">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<org.madebyalex.myperiod.CustomImageView
android:id="@+id/chart_cell_background"
android:src="@drawable/ball"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:gravity="center_vertical"
android:adjustViewBounds="true"/>
<TextView
android:id="@+id/chart_month_number"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:text="AAAA"
android:textColor="@color/saltpan"
android:textSize="35sp"
android:gravity="center_horizontal" />
</RelativeLayout>
</LinearLayout>
此代码正常运行。我在其他部分使用它,并完全呈现布局。此布局用于具有此ctor的类中:
public ChartMonthItem( Context context, RecyclerViewItemClickListener itemClickListener ){
super( context );
this.context = context;
this.itemClickListener = itemClickListener;
selected = false;
View view = LayoutInflater.from( context ).inflate( R.layout.chart_select_option_text_image, this );
CustomImageView backgroundMonth = ( CustomImageView )findViewById( R.id.chart_cell_background );
backgroundMonth.setMinimumWidth( 100 );
drawable = backgroundMonth.getDrawable();
chartMonthNumber = ( TextView )findViewById( R.id.chart_month_number );
}
为了测试,我强制将ImageView的最小宽度设置为100。调用invalidate()也不起作用。即使采用这种方法,它仍然具有零宽度。 我希望通过这种方法确保最小宽度,并且创建的ImageViews将根据其父级具有适当的宽度。
我做错了什么?