除非屏幕小于那个宽度,否则可以将子宽度设置为固定宽度吗?
即。我希望下面的CardView正常400dp,除非它在一个小屏幕上,此时它应该是屏幕宽度(减去边距)......
<cdudigital.com.conjugator.MyLinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:orientation="vertical"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
android:paddingBottom="@dimen/activity_vertical_margin"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
tools:context=".GameActivity">
<android.support.v7.widget.CardView
xmlns:card_view="http://schemas.android.com/apk/res-auto"
android:id="@+id/card_view"
android:layout_gravity="center"
android:gravity="center"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
card_view:cardCornerRadius="4dp"
card_view:cardElevation="3dp">
</android.support.v7.widget.CardView>
</cdudigital.com.conjugator.MyLinearLayout>
答案 0 :(得分:1)
获取屏幕DP
DisplayMetrics displayMetrics = context.getResources().getDisplayMetrics();
float dpWidth = displayMetrics.widthPixels / displayMetrics.density;
并检查它是否低于400
if(dpWidth < 400){
cardView.setLayoutParams(new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.MATCH_PARENT));
} else {
cardView.setLayoutParams(new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT,(400 * displayMetrics.density + 0.5f)));
}
或者在XML
中android:layout_width="match_parent"
android:maxWidth="400dp"