2015-02-11 78 views
9

我有一個recylcler視圖,但它似乎沒有實現setGravity方法。RecyclerView重力

我的列表是水平對齊的,但我需要它居中。我怎麼做?

fragment_my_zone_item_controlled.xml

<?xml version="1.0" encoding="utf-8"?> 
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" 
    android:layout_width="match_parent" 
    android:layout_height="match_parent" 
    android:background="@color/dark_grey"> 

    <FrameLayout 
     android:id="@+id/fragment_my_zone_item_controlled_content" 
     android:layout_width="match_parent" 
     android:layout_height="match_parent" 
     android:layout_below="@+id/fragment_my_zone_item_controlled_tabs" 
     android:layout_marginBottom="12dp" 
     android:layout_marginTop="12dp" /> 

    <android.support.v7.widget.RecyclerView 
     android:id="@+id/fragment_my_zone_item_controlled_tabs" 
     android:layout_width="match_parent" 
     android:layout_height="44dp" 
     android:background="@color/action_bar_color" 
     android:scrollbars="none" /> 

</RelativeLayout> 

This is how it looks

這是它的外觀,我需要它爲中心

謝謝你們

回答

5

我知道這是非常晚回答,可能是其他人得到了這個幫助,所以請嘗試添加這樣的

<android.support.v7.widget.RecyclerView 
     android:id="@+id/fragment_my_zone_item_controlled_tabs" 
     android:layout_width="wrap_content" 
     android:layout_height="44dp" 
     android:layout_centerHorizontal="true" 
     android:background="#dddddd" 
     android:scrollbars="none" /> 

添加android:layout_centerHorizontal="true"方法

+2

另一個重要的變化是將'android:layout_width'設置爲'wrap_content'。 – 2017-05-31 17:47:25

+0

這會將一個'RecyclerView'放在它的父對象'RelativeLayout'中。但是這對Recycler的物品沒有影響,或者Recycler的寬度是'match_parent'。 – 2017-06-07 21:06:16

+0

RecyclerView沒有'layout_center_horizo​​n'這樣的屬性 – 2017-08-23 11:48:19

1

如果其他的答案不幫你,我在RecyclerView面臨的一個問題,其中內容沒有得到有效包裹,導致佈局被強迫一個角落或其他。

我的答案是創建一個擴展LinearLayoutManager的自定義類。您可以嘗試此操作,然後以編程方式設置重力。

這是我的question的鏈接,以及我得到idea for my answer的帖子。

1

(如果有人正在尋找像我這樣的答案),我嘗試了兩種解決方案,並沒有爲我工作,這就是我所做的。我計算出屏幕的寬度&我看來寬度,然後在我的RecyclerView.ViewHolder我加緣至左爲我的視圖(這是在我的情況比)

DisplayMetrics metrics = new DisplayMetrics(); 
context.getWindowManager().getDefaultDisplay().getMetrics(metrics); 
int screenWidth = metrics.widthPixels; 
long ratio = screenWidth * 90/100; 
int margin = (int) ((screenWidth - ratio)/2); 
LinearLayout.LayoutParams lp1 = new LinearLayout.LayoutParams((int) ratio, ViewGroup.LayoutParams.WRAP_CONTENT); 
lp1.gravity = Gravity.CENTER_VERTICAL; 
lp1.setMargins(margin, 0, 0, 0); 
itemLayoutView.setLayoutParams(lp1); 

這是凌亂的解決方案,但我找不到其他

0

theLazyFinder解決方案的工作原理,但萬一你想爲RV有不同的背景顏色,然後將其添加到FrameLayout並將其重力設置爲中心。

<FrameLayout 
     android:layout_width="match_parent" 
     android:layout_height="wrap_content" 
     android:background="@color/colorWhite"> 

     <android.support.v7.widget.RecyclerView 
      android:layout_width="wrap_content" 
      android:layout_height="wrap_content" 
      android:layout_gravity="center" 
      /> 

</FrameLayout>