2015-07-05 22 views
0

我希望我的聊天氣泡可以在不同用戶發送消息時移動到右側,但由於某種原因它仍停留在同一側。這是我試過的:如何從alignParentLeft切換到alignParentRIght?

RelativeLayout.LayoutParams params = (RelativeLayout.LayoutParams) holder.bubble.getLayoutParams(); 
if (message.getPersonId() == MainActivity.getUser().getUserId()) { 
     params.addRule(RelativeLayout.ALIGN_PARENT_RIGHT, 0); 
     params.addRule(RelativeLayout.ALIGN_PARENT_LEFT, RelativeLayout.TRUE); 
} else { 
     params.addRule(RelativeLayout.ALIGN_PARENT_LEFT, 0); 
     params.addRule(RelativeLayout.ALIGN_PARENT_RIGHT, RelativeLayout.TRUE); 
} 
holder.bubble.setLayoutParams(params); 

有什麼我做錯了嗎?我也嘗試過params.removeRule(int),但它不起作用,另外我更喜歡遠離這一點,因爲我希望儘可能確保操作系統的可用性。

回答

1

您可以簡單地添加參數,這樣way-

RelativeLayout.LayoutParams rlp = new RelativeLayout.LayoutParams 
(
     RelativeLayout.LayoutParams.MATCH_PARENT, 
     RelativeLayout.LayoutParams.MATCH_PARENT 
); 

------------------------------------ 
---------------------------------- 
// Creating a new TextView 
TextView tv = new TextView(this); 
tv.setText(d.getName()); 
tv.setTextSize(25); 

// Defining the layout parameters of the TextView 
RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams(
     RelativeLayout.LayoutParams.WRAP_CONTENT, 
     RelativeLayout.LayoutParams.WRAP_CONTENT); 
     lp.addRule(RelativeLayout.ALIGN_PARENT_RIGHT); 

// Setting the parameters on the TextView 
tv.setLayoutParams(lp); 
b.setLayoutParams(lp); 

// Adding the TextView to the RelativeLayout as a child 

我認爲,如果按照這種方式,不會有任何問題。

+0

謝謝!這對我有效! – silverAndroid

0

看來你沒有正確使用adRule()。請更改,然後再試一次:

RelativeLayout.LayoutParams params = (RelativeLayout.LayoutParams) holder.bubble.getLayoutParams(); 
if (message.getPersonId() == MainActivity.getUser().getUserId()) { 
    params.removeRule(RelativeLayout.ALIGN_PARENT_RIGHT); 
    params.addRule(RelativeLayout.ALIGN_PARENT_LEFT); 
} 
else { 
    params.removeRule(RelativeLayout.ALIGN_PARENT_LEFT); 
    params.addRule(RelativeLayout.ALIGN_PARENT_RIGHT); 
} 
holder.bubble.setLayoutParams(params); 
+0

請詳細說明你的意思是正確使用'addRule()'。 'addRule(int,int)'是SDK提供的一種方法。 – silverAndroid

+0

[RelativeLayout.LayoutParams.addRule(int,int)](http://developer.android.com/reference/android/widget/RelativeLayout.LayoutParams.html#addRule(int,int))適用於第二個參數爲一個視圖ID,即當你需要將視圖與另一個視圖對齊時。 [RelativeLayout.LayoutParams.addRule(int)](http://developer.android.com/reference/android/widget/RelativeLayout.LayoutParams.html#addRule(int))適用於想要移動視圖的情況parent(RelativeLayout容器)作爲第二個參數。 –