ImageView宽度为设备宽度Android的50%

时间:2017-08-09 15:46:47

标签: android imageview android-cardview

在开始之前我应该​​说我是Android开发的初学者:) 我正在使用网格recyclerView并将列数设置为2。 我的ImageView中只有一个cardView,我不知道如何将此卡(或图片)设置为屏幕宽度的50%,因为当我用数字设置其高度和宽度时我在不同的屏幕尺寸上遇到问题。

我使用layout_weight阅读并尝试了一些方法,但它不适用于此cardView

  

card.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="horizontal"
    android:layout_width="200dp"
    android:layout_height="200dp"
    >

    <ImageView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/list_photo_double_view"
        android:src="@drawable/e48"
        />


</LinearLayout>

我怎么能在这里做到这一点?

提前致谢

2 个答案:

答案 0 :(得分:1)

这种事情在ConstraintLayout中出现过。您可以详细了解herehere

不使用此库我只能建议您使用LinearLayout这样:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="horizontal">

    <FrameLayout
        android:layout_width="0dp"
        android:layout_height="match_parent"
        android:layout_weight="1" />

    <ImageView
        android:layout_width="0dp"
        android:layout_height="match_parent" 
        android:layout_weight="2" />

    <FrameLayout
        android:layout_width="0dp"
        android:layout_height="match_parent"
        android:layout_weight="1" />
</LinearLayout>

如你所见。我使用android:weight LinearLayout属性来使ImageView占据屏幕宽度的50%,如果linearlayout占据整个屏幕。

无需在LinearLayout中定义weight_sum,只需在子布局中使用layout_weight并指定值即可。如果要分别垂直或水平制作分区,请务必将heightwidth设置为0.

PS。 layout_weight仅适用于LinearLayouts。

答案 1 :(得分:0)

通过使用百分比相对布局,我们可以轻松实现这一目标。在此,我将解释如何实现percentRelativeLayout

<强>相关性:

compile 'com.android.support:percent:23.3.0'

在你的布局文件中,

<android.support.percent.PercentRelativeLayout
  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="match_parent"
  android:paddingBottom="@dimen/activity_vertical_margin"
  android:paddingLeft="@dimen/activity_horizontal_margin"
  android:paddingRight="@dimen/activity_horizontal_margin"
  android:paddingTop="@dimen/activity_vertical_margin"
  tools:context=".MainActivity">


  <ImageView
         app:layout_widthPercent="match_parent"
         app:layout_heightPercent="50%"/>

</android.support.percent.PercentRelativeLayout>

希望这有用:)