2017-08-09 106 views
0

開始之前我應該​​說我是Android開發的初學者:) 我正在使用網格recyclerView並已將列數設置爲2 我僅限於在我的cardView中有一個ImageView,我不知道如何使此卡(或圖像)爲屏幕寬度的50%,因爲當我使用數字設置其高度和寬度時,我在不同的屏幕尺寸上遇到問題。ImageView寬度爲設備寬度的50%Android

我閱讀並嘗試了一些與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> 

我怎麼能做到這一點嗎?

在此先感謝

+0

'CardView'從'FrameLayout'延伸。如果你真的想使用'CardView',在CardView中放置一個'LinearLayout',那麼你可以使用attr layout_weight –

回答

1

這樣的事情在ConstraintLayout已經appered。你可以閱讀更多關於它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> 

正如你所看到的。如果linearlayout佔據整個屏幕,我使用LinearLayoutandroid:weight屬性使ImageView佔用屏幕寬度的50%。

LinearLayout中沒有必要定義weight_sum,只需在子佈局中使用layout_weight並賦值即可。如果要分別垂直或水平分區,請務必將heightwidth設置爲0。

PS。 layout_weight僅適用於LinearLayouts。

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> 

希望這是有益:)