Home > database >  LayoutParams is making my AppCompatTextView to disappear
LayoutParams is making my AppCompatTextView to disappear

Time:12-24

I have the following ContstraintLayout:

    <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>

I want to change the marginTop value in code:

This is what I have done but the AppCompatTextView is disappearing:

        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);


}

CodePudding user response:

Try to modify the existing layout params instead of creating new ones. By creating new params, you are likely losing the other information you have defined in your XML, such as your constraints. I'm going from memory, but I would try something like this:

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

You may also be able to clone the existing layoutparams instead of modifying the existing ones:

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);

Edit: Also, consder that setMargins accepts dimensions as pixels as an argument, not density-independent pixels. This means that if you just set an int value like 10, then your layout will not scale well for different android devices. You can convert the value to DP yourself, or define the value in xml and use Resources::getDimensionPixelOffest.

  • Related