2016-06-07 58 views
0

我在應用內部製作了一個messenger功能,並希望根據持有者傳遞的值(必須是START或END)來更改佈局引力。一切工作正常,除了重力。它在START開始供所有持有者使用。有沒有解決方法?Android RecyclerView問題中的不同佈局

@Override 
public void onBindViewHolder(MyViewHolder holder, int position) { 
    Message message = mMessageList.get(position); 
    if(message.getSender().equals("System")){ 
     holder.content.setBackgroundResource(R.drawable.message_bubble_out); 
     holder.content.setTextColor(Color.parseColor("#000000")); 
     holder.messageLayout.setGravity(Gravity.END); 
    } 
    holder.content.setText(message.getContent()); 
} 

消息佈局XML:

<?xml version="1.0" encoding="utf-8"?> 
<LinearLayout 
    android:id="@+id/message_wrapper" 
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content" 
    android:layout_gravity="end" 
    xmlns:android="http://schemas.android.com/apk/res/android"> 

     <TextView 
      android:id="@+id/message_content" 
      android:layout_width="250dp" 
      android:layout_height="wrap_content" 
      android:background="@drawable/message_bubble_out" 
      android:text="Hi, rangertS!" 
      android:textColor="#FFFFFF" /> 

</LinearLayout> 

messageLayout定義:

messageLayout = (LinearLayout) view.findViewById(R.id.message_wrapper); 
+0

'messageLayout'的類型是什麼? – ridsatrio

+0

messageLayout是一個LinearLayout – NickitaX

+0

你可以更新你的問題還包括持有者和'messageLayout'的定義嗎?因爲從上面給出的片段來看,這個問題似乎在別的地方。 – ridsatrio

回答

1

好了,現在你給了我們您的問題更詳細闡述的解釋,我想我知道答案。

重力似乎不是在這裏責備..正如我所說,你的約束邏輯是關鍵。

這裏真正的罪魁禍首是你佈置消息佈局的方式。讓我們來看看我指出下面幾行:

<LinearLayout 
    android:id="@+id/message_wrapper" 
    android:layout_width="wrap_content" <--- Use match_parent instead 
    android:layout_height="wrap_content" 
    android:layout_gravity="end" 
    xmlns:android="http://schemas.android.com/apk/res/android"> 

     <TextView 
      android:id="@+id/message_content" 
      android:layout_width="250dp" <--- Use wrap_content instead 
      android:layout_height="wrap_content" 
      android:background="@drawable/message_bubble_out" 
      android:text="Hi, rangertS!" 
      android:textColor="#FFFFFF" /> 

</LinearLayout> 

你可以看到你的問題的兩個根本原因在註解段上面我給了。讓我們更多地討論這一點:

  1. 你宣佈你的LinearLayout寬度wrap_content意味着重力將永遠不會在這方面發揮的作用。爲什麼?那麼因爲佈局總是和它的內容一樣大小!儘量讓你的LinearLayout和它的父母一樣寬,你會看到重力的影響。

  2. 你的TextView的250dp至少從我的POV來說太大了。有一點理由使其TextView比它包含的實際文本更大。請嘗試在此處使用wrap_content。

希望這有助於! :)

+0

非常感謝,先生!你做到了:)我花了幾個小時試圖在JAVA中找到一個bug,而解決方案是在一個佈局中......它的確有助於:) Hooraaay! – NickitaX

+0

我很樂意提出你的答案,但不幸的是我沒有足夠的聲望。 – NickitaX