java - 限制聊天应用中布局宽度的大小
问题描述
我正在构建的应用程序需要一个简单的聊天模块。除了限制出现在 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));
}
}
解决方案
推荐阅读
- drupal - 搜索字段 - 使用用户位置自动预填充
- sql - SQL:表循环期间金额不增加
- mysql - Safari 无法连接到 Mac 中的 localhost Xampp
- apache-spark - HDP3.1.4 - Spark2 与 Hive 仓库连接器错误使用 spark-submit 和 pyspark shell:KeeperErrorCode = ConnectionLoss
- java - 超出范围的错误我已将此代码从数组更改为数组列表,现在它给出了绑定错误?
- vue.js - VueJS发出的事件没有被父组件拾取
- javascript - 使用按钮加速和减速球
- java - 无法从 Maven 依赖项中找到资源文件
- docker - 如何在我的 PATH 中设置 docker-credential-ecr-login 在 GitLab CI 中的任何其他内容之前
- python - Tkinter 与 openweather