首页 > 解决方案 > 限制聊天应用中布局宽度的大小

问题描述

我正在构建的应用程序需要一个简单的聊天模块。除了限制出现在 Recyclerview 的聊天屏幕中的每个聊天气泡的宽度之外,我已经完成了所有工作。

设计逻辑是,如果聊天气泡占用的宽度大于等于屏幕宽度的 70%,则视图将被限制为宽度的 70%,否则将根据需要占用多少宽度。您可以在此图像中观察聊天气泡宽度是如何受到限制的。(在 UI 完全以编程方式构建的 iOS 中,这要容易得多。)

所以我所做的是在 XML 中为左定义初始案例:

<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    xmlns:app="http://schemas.android.com/apk/res-auto">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/chat_message"
        android:textColor="@color/black"
        android:fontFamily="@font/nexabold"
        android:textSize="16sp"
        android:layout_margin="16dp"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintBottom_toBottomOf="parent"
        android:background="@drawable/background_chat_left"
        android:padding="8dp"/>

</androidx.constraintlayout.widget.ConstraintLayout>

然后是右边:

<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    xmlns:app="http://schemas.android.com/apk/res-auto">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/chat_message"
        android:textColor="@color/fullWhite"
        android:fontFamily="@font/nexabold"
        android:textSize="16sp"
        android:layout_margin="16dp"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintBottom_toBottomOf="parent"
        android:background="@drawable/background_chat_right"
        android:padding="8dp"/>

</androidx.constraintlayout.widget.ConstraintLayout>

最后,在 Recyclerview 的适配器中的绑定视图持有者方法中,我执行以下操作。我的想法是我在 XML 中打开开始(传出的 msg)/结束(传入的 msg)约束并填充 textview。如果 textviews 超过 70%,则限制宽度。但是,这不起作用,我不知道为什么。无论如何,我最终都会将文本溢出屏幕。在此处输入图像描述

   @Override
    public void onBindViewHolder(@NonNull MessagesViewHolder holder, int position) {
        holder.tvMessage.setText(messagesArray.get(position).getBody());

        Context context = holder.tvMessage.getContext();
        DisplayMetrics displayMetrics = context.getResources().getDisplayMetrics();
        int screenWidth = displayMetrics.widthPixels;

        ViewGroup.LayoutParams layoutParams = holder.tvMessage.getLayoutParams();
        if (layoutParams.width >= screenWidth * 0.7) {
            holder.tvMessage.setLayoutParams(new ViewGroup.LayoutParams((int) (screenWidth * 0.7), ViewGroup.LayoutParams.WRAP_CONTENT));
        }
    }

标签: javaandroid

解决方案


推荐阅读