android 布局参数使我的AppCompatTextView消失

mwecs4sa  于 2022-12-25  发布在  Android
关注(0)|答案(1)|浏览(146)

我有以下约束布局:

<androidx.constraintlayout.widget.ConstraintLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        >
        <androidx.appcompat.widget.AppCompatTextView
            android:id="@+id/my_text"
            android:layout_width="0dp"
            android:layout_height="0dp"
            android:text="@string/txt_string"

            app:layout_constraintBottom_toBottomOf="@id/one"
            app:layout_constraintEnd_toStartOf="@id/two"
            app:layout_constraintStart_toEndOf="@id/three"
            app:layout_constraintTop_toTopOf="@id/four"
            android:layout_marginTop="@dimen/margin_dim"
            />
    </androidx.constraintlayout.widget.ConstraintLayout>

我想在代码中更改marginTop值:
这是我所做的,但AppCompatTextView正在消失:

AppCompatTextView mytext;
    
    private void onCreate(@Nullable Bundle savedInstanceState) {
    
          super.onCreate(savedInstanceState);
            setContentView(R.layout.my_layout);
    
            mytext = findViewById(R.id.my_text);
    
ConstraintLayout.LayoutParams params = new ConstraintLayout.LayoutParams(ConstraintLayout.LayoutParams.WRAP_CONTENT, ConstraintLayout.LayoutParams.WRAP_CONTENT);
        params.setMargins(0,10,0,0);
mytext.setLayoutParams(params);

}
ajsxfq5m

ajsxfq5m1#

尝试修改现有的布局参数,而不是创建新的布局参数。创建新的布局参数可能会丢失在XML中定义的其他信息,例如约束。我将根据记忆进行操作,但我将尝试以下操作:

ConstraintLayout.LayoutParams params = (ConstraintLayout.LayoutParams) mytext.getLayoutParams();
params.setMargins(0,10,0,0);
mytext.setLayoutParams(params);

您还可以克隆现有的layoutparams,而不是修改现有的layoutparams:

final ConstraintLayout.LayoutParams current = 
  (ConstraintLayout.LayoutParams) mytext.getLayoutParams();
final ConstraintLayout.LayoutParams params = 
  new ConstraintLayout.LayoutParams(current);
params.setMargins(0,10,0,0);
mytext.setLayoutParams(params);

**编辑:**另外,考虑到setMargins接受像素作为参数,而不是密度无关像素。这意味着如果你只是设置一个int值,如10,那么你的布局将无法很好地缩放不同的android设备。你可以将该值转换为DP yourself,或在xml中定义该值并使用Resources::getDimensionPixelOffest

相关问题