我对聊天 View 布局有疑问。
我的布局中有一些 TextView 。其中一些的layout_width等于match_parent并且gravity设置为right。 我的问题是这样的:textview 的背景填充了textview 可用的所有空间,而不仅仅是textview 中的文本。 如何设置 TextView 的背景以仅填充我的文本?
这是我列表的适配器:
private class CommentAdapter extends ArrayAdapter<COMMENT> {
RelativeLayout listLayout;
RelativeLayout.LayoutParams paramsTxt;
RelativeLayout.LayoutParams paramsImg;
public CommentAdapter(Context context, ArrayList<COMMENT> comments) {
super(context, -1, -1, comments);
listLayout = new RelativeLayout(CommentPage.this);
paramsTxt = new RelativeLayout.LayoutParams(
RelativeLayout.LayoutParams.MATCH_PARENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
paramsImg = new RelativeLayout.LayoutParams(
RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
paramsImg.height = width_square*7;
paramsImg.width = width_square*7;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
final ViewHolder holder;
COMMENT single_comment = null;
RequestOptions options = new RequestOptions();
options.centerCrop();
if (convertView == null) {
// if convertView is null
convertView = getLayoutInflater().inflate(R.layout.row_comment, parent, false);
holder = new ViewHolder();
// initialize views
holder.textView = convertView.findViewById(R.id.comment_text);
holder.imageView = convertView.findViewById(R.id.comment_image);
convertView.setTag(holder);
} else {
holder = (CommentPage.ViewHolder) convertView.getTag();
holder.imageView.setBackground(null);
}
single_comment = getItem(position);
if(single_comment.senderId.equals(myId)) {
holder.textView.setGravity(Gravity.RIGHT);
paramsTxt.setMargins(width_square*20,width_square*2,
width_square*5,width_square*2);
holder.textView.setBackgroundResource(R.drawable.bubble_right);
holder.textView.setLayoutParams(paramsTxt);
} else {
paramsTxt.setMargins(width_square*5,width_square*2,
width_square*20,width_square*2);
paramsImg.addRule(RelativeLayout.ALIGN_PARENT_LEFT);
paramsTxt.addRule(RelativeLayout.RIGHT_OF, R.id.comment_image);
holder.imageView.setImageResource(R.drawable.default_profile);
holder.textView.setBackgroundResource(R.drawable.bubble_left);
paramsImg.setMargins(width_square*5,width_square*2,
0,width_square*2);
holder.imageView.setLayoutParams(paramsImg);
holder.textView.setLayoutParams(paramsTxt);
}
holder.textView.setText(single_comment.text);
return convertView;
}
}
预先感谢您的帮助。
最佳答案
只需使用 "wrap_content"
而不是 "match_parent"
作为这些 TextView 上的宽度。
:)
关于android - 设置 TextView 的背景仅填充我的文本 - Java,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49706183/