Android Toolbar 中 TextView 控件右对齐实现方法
在 Toolbar 中将 TextView 放在最右边,可以将 TextView 放在一个 RelativeLayout 中,并将其设置为 Toolbar 的子视图。然后,可以使用 RelativeLayout.LayoutParams 来将 TextView 放在 Toolbar 的右侧。以下是示例代码:
在 XML 布局文件中:
<androidx.appcompat.widget.Toolbar
android:id="@+id/toolbar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="@color/colorPrimary"
android:elevation="4dp"
app:titleTextColor="@android:color/white">
<RelativeLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<TextView
android:id="@+id/title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Title"
android:textColor="@android:color/white"
android:textSize="18sp" />
<TextView
android:id="@+id/right_text"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Right Text"
android:textColor="@android:color/white"
android:textSize="14sp"
android:layout_alignParentRight="true"
android:layout_centerVertical="true" />
</RelativeLayout>
</androidx.appcompat.widget.Toolbar>
在 Java 代码中:
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
TextView rightText = findViewById(R.id.right_text);
RelativeLayout.LayoutParams params = (RelativeLayout.LayoutParams) rightText.getLayoutParams();
params.addRule(RelativeLayout.ALIGN_PARENT_RIGHT);
rightText.setLayoutParams(params);
原文地址: https://www.cveoy.top/t/topic/oXlV 著作权归作者所有。请勿转载和采集!