我有一些在程序中创建textView的问题,不知道该怎么解决。
问题如下:
- 边距,我不想让我的TextView彼此粘在一起。
- 文本没有像标题中那样居中在drawable中
- 我想要昵称用户的消息靠右对齐,Nick的消息靠左对齐。
为此,我有这两个函数:
private void appendSenderText(String message) {
TextView msg = new TextView(ChatActivity.this);
msg.setBackgroundResource(R.drawable.rectangle);
msg.setText(message);
msg.setPadding(10, 10, 10, 10);
msg.setTextColor(getResources().getColor(R.color.white));
FrameLayout.LayoutParams params = new FrameLayout.LayoutParams(LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT, Gravity.LEFT);
params.setMargins(10, 10, 10, 10);
msg.setLayoutParams(params);
LinearLayout chat = (LinearLayout) findViewById(R.id.chatLayout);
chat.addView(msg);
}
private void appendReceiverText(String message) {
TextView msg = new TextView(ChatActivity.this);
msg.setBackgroundResource(R.drawable.rectangle);
msg.setText(message);
msg.setPadding(10, 10, 10, 10);
msg.setTextColor(getResources().getColor(R.color.white));
FrameLayout.LayoutParams params = new FrameLayout.LayoutParams(LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT, Gravity.RIGHT);
params.setMargins(10, 10, 10, 10);
msg.setLayoutParams(params);
LinearLayout chat = (LinearLayout) findViewById(R.id.chatLayout);
chat.addView(msg);
}
看起来它不起作用。我也检查了函数是否被正确调用。
我注意到在我的标题的XML文件中,我指定了layout_gravity而不是gravity。
编辑:我按照你建议使用了ListView,一切都正常工作,但我仍然有这个文本不居中的问题,尽管我使用了msg.setGravity(gravity.CENTER)。
可能我的drawable有问题。
这是我圆角矩形的xml文件。奇怪的是,当我在xml文件中创建我的Textview时,文本是居中的,而当我想要以编程方式创建时,情况就不同了。
这是我的drawable代码。
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle">
<gradient
android:startColor="@color/drk_button"
android:endColor="@color/lgt_button"
android:angle="90">
</gradient>
<corners android:radius="7dip" />
<stroke
android:width="1px"
android:color="@color/drk_button" />
</shape>
这里是我创建textView的代码。
Message message = (Message) this.getItem(position);
ViewHolder holder;
if(convertView == null)
{
holder = new ViewHolder();
convertView = LayoutInflater.from(mContext).inflate(R.layout.sms_row, parent, false);
holder.message = (TextView) convertView.findViewById(R.id.message_text);
convertView.setTag(holder);
}
else
holder = (ViewHolder) convertView.getTag();
holder.message.setText(message.getMessage());
holder.message.setTextSize(17);
holder.message.setGravity(Gravity.CENTER);
LayoutParams lp = (LayoutParams) holder.message.getLayoutParams();
if(message.isMine())
{
holder.message.setBackgroundResource(R.drawable.rectangle);
lp.gravity = Gravity.LEFT;
}
else
{
holder.message.setBackgroundResource(R.drawable.rectangledest);
lp.gravity = Gravity.RIGHT;
}
holder.message.setLayoutParams(lp);
holder.message.setTextColor(Color.WHITE);
return convertView;
}
ListView
并查看一些示例聊天应用程序代码。 - Spring Breaker