如何从alignParentLeft切换到alignParentRIght?

时间:2015-07-05 23:36:09

标签: android android-layout

当其他用户发送消息时,我希望我的聊天气泡移动到右侧,但出于某种原因,它仍保持在同一侧。这就是我尝试过的:

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),但它没有工作,我更愿意远离那个,因为我想确保尽可能多的可用性。

2 个答案:

答案 0 :(得分:1)

您可以像这样添加参数 -

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

我认为,如果你按照这种方式行事,就不会有任何问题。

答案 1 :(得分: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);