Android中如何将旋转后的View/Button固定在ConstraintLayout左侧?
问题描述
编辑:仅使用translateX即可实现(详见评论及已采纳答案),我之前居然没注意到这点。
在Android开发中,我希望将一个普通按钮旋转90度后紧贴ConstraintLayout的左侧,但实际操作后,按钮与屏幕左侧仍存在明显间距。
理想效果:按钮垂直放置,完全紧贴布局左侧边缘,无间距。
我的XML布局文件如下:
<?xml version="1.0" encoding="utf-8"?> <androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent"> <Button android:id="@+id/button" android:layout_width="wrap_content" android:layout_height="wrap_content" android:rotation="90" android:text="My example button" app:layout_constraintBottom_toBottomOf="parent" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toTopOf="parent" /> </androidx.constraintlayout.widget.ConstraintLayout>
实际效果:按钮旋转90度后,与布局左侧存在明显间距,未紧贴边缘。
问题原因似乎是先应用左侧、顶部及底部约束,再执行旋转操作。我尝试用Java代码修复但无效:
Button button = view.findViewById(R.id.button); button.setRotation(90); // already done, but doesn't matter // constrain to left side after after rotation (doesn't help) ConstraintSet constraintSet = new ConstraintSet(); constraintSet.clone((ConstraintLayout) view); constraintSet.connect(button.getId(), ConstraintSet.START, ConstraintSet.PARENT_ID, ConstraintSet.START); constraintSet.applyTo((ConstraintLayout) view); // attempt to fix positioning with margins (doesn't move anything at all) ViewGroup.MarginLayoutParams params = (ViewGroup.MarginLayoutParams) btnTest.getLayoutParams(); params.setMargins(-100, 0, 0, -100); // left, top, right, bottom btnTest.setLayoutParams(params);
我还尝试在XML中修改边距,同样毫无效果。编辑:负边距在旧项目中无效,但在新测试项目中有效,怀疑是使用了旧版本库(可能是通过appcompat 1.1.0间接引入的material库)导致的。
请问有谁知道如何实现我想要的效果?感谢帮助!
内容的提问来源于stack exchange,提问作者Jordi
相关产品推荐
相关产品推荐

