我想在我的 Android 程序中以编程方式为 2 TextView 设置参数,但我遇到了问题。这是一段有趣的代码:
private void setChatItemStyle(Boolean mineMsg, ChatViewHolder holder) {
if(mineMsg) {
holder.params.gravity = Gravity.END;
holder.autore.setTextColor(Color.BLUE);
}else{
holder.params.gravity = Gravity.START;
holder.autore.setTextColor(Color.MAGENTA);
}
holder.autore.setLayoutParams(holder.params);
holder.messaggio.setLayoutParams(holder.params);
}
现在的问题是;设置了文本的颜色,但没有设置重力。 我该如何解决?
TextView Cioscos 及其各自的文本应显示在右侧,而不是 Activity 左侧的 Peter 文本下方。
这是我的 ChatViewHolder:
public class ChatViewHolder extends RecyclerView.ViewHolder {
TextView autore, messaggio;
LinearLayout.LayoutParams params;
public ChatViewHolder(View itemView) {
super(itemView);
autore = itemView.findViewById(R.id.tv_autore);
messaggio = itemView.findViewById(R.id.tv_messaggio);
params = (LinearLayout.LayoutParams) autore.getLayoutParams();
}
}
只有消息在右边,但它仍然没有在屏幕的右边。
XML 文件:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:visibility="visible">
<TextView
android:id="@+id/tv_autore"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:paddingLeft="10dp"
android:paddingRight="10dp"
android:text="Autore"
android:textColor="@color/colorPrimaryDark"
android:textSize="24sp"
android:textStyle="bold" />
<TextView
android:id="@+id/tv_messaggio"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="10dp"
android:text="Messaggio" />
</LinearLayout>
最佳答案
当我们没有 TextView
的布局时很难回答,它应该在您的 ChatViewHolder
中。
关于 gravity
我能说的是,gravity
有两种类型。
LayoutParams
中的重力等于 xml 中的layout_gravity
(TextView
的布局)View
中的 Gravity 等于 xml 中的gravity
)
在你的情况下:
- 如果您的
TextView
宽度为WRAP_CONTENT
,将会工作 - 如果您的
TextView
的宽度为MATCH_PARENT
,将会工作
针对您的情况的一种方法:
private void setChatItemStyle(Boolean mineMsg, ChatViewHolder holder) {
int gravity = Gravity.START;
if (mineMsg) {
gravity = Gravity.END;
holder.autore.setTextColor(Color.BLUE);
} else {
holder.autore.setTextColor(Color.MAGENTA);
}
holder.autore.setGravity(gravity);
holder.messaggio.setGravity(gravity);
}
同时在您的 xml 文件中将 TextViews
设置为 match_parent
我使用 kotlin,所以语法可能有误?对不起,如果我遗漏了什么,你明白了......
关于android - LinearLayout 中的 TextView 参数无法以编程方式工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55851483/