设置问题在View Holder模式中查看参数

时间:2014-06-23 07:28:13

标签: android android-layout android-listview android-linearlayout android-relativelayout

我正在使用带有ListView的ArrayAdpater。我使用自己的布局自定义了每个项目,其中包括顶级视图层次结构,RelativeLayout - > LinearLayout - >其他内心观点。

我正在回收视图,而我正在使用View Holder模式。适配器内的getView()是:

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        View rowView = convertView;
        ViewHolder holder;

        if(rowView == null){
            LayoutInflater inflater = (LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE);            
            rowView = inflater.inflate(R.layout.custom_row, parent, false);

            holder = new ViewHolder();
            holder.tvMessage = (TextView)rowView.findViewById(R.id.chat_text_message);
            holder.tvUser = (TextView)rowView.findViewById(R.id.user);
            holder.llMessageBubble = (LinearLayout)rowView.findViewById(R.id.message_bubble);

            rowView.setTag(holder);
        }else {

            holder = (ViewHolder) rowView.getTag();
        }
            setRow(holder, messageList.get(position).getUser(),messageList.get(position).getTextMessage());

        return rowView;
    }

哪里

public static class ViewHolder{
     TextView tvMessage;
     TextView tvUser;
     LinearLayout llMessageBubble;
}

和setRow方法定义为:

    private void setRow(ViewHolder holder, String user, String message){
        if(user.equals("Me")){

            RelativeLayout.LayoutParams params = (RelativeLayout.LayoutParams)holder.llMessageBubble.getLayoutParams();
            params.addRule(RelativeLayout.ALIGN_PARENT_RIGHT);

            holder.llMessageBubble.setLayoutParams(params);
        }else{

            RelativeLayout.LayoutParams params = (RelativeLayout.LayoutParams)holder.llMessageBubble.getLayoutParams();
            params.addRule(RelativeLayout.ALIGN_PARENT_LEFT);

            holder.llMessageBubble.setLayoutParams(params);
        }
        holder.tvMessage.setText(message);
        holder.tvUser.setText(user);
    }

当ListView第一次显示时,一切正常,所以我可以看到我的LinearLayout(在RelativeLayout内)基于字符串用户向左或向右对齐。 但是当我向上和向下滚动一段时间时会出现问题:在一段时间之后,所有LinearLayout s都与父级中的右对齐。似乎回收中存在问题。

1 个答案:

答案 0 :(得分:1)

您似乎不断在视图中添加规则。而不是:

RelativeLayout.LayoutParams params = (RelativeLayout.LayoutParams)holder.llMessageBubble.getLayoutParams();

尝试这个(或任何符合您需求的构造函数):

RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT);

希望它有所帮助。

此致 Steffen Vangsgaard