javaandroidviewandroid-linearlayoutlayoutparams

Android: calling setPadding() on a view doesn't work when I also set the layoutParams on the view


If I call setPadding() on a view, I can successfully set the padding, however, if I first set the layoutParams and then the padding, or set the padding and then set the layoutParams, the padding is not applied.

Demonstration:

    //This doesn't work
    textView.setLayoutParams(linearLayoutParams);
    textView.setPadding(0, 100, 0 , 0);

    //This doesn't work either
    testView.setPadding(0, 100, 0 , 0);
    textView.setLayoutParams(linearLayoutParams);

    //This does work
    textView.setPadding(0, 100, 0 , 0);

Does anyone know how to use setLayoutParams() and setPadding() at the same time, or why setLayoutParams() is stopping setPadding() from working?

Edit: More detail:

I call this method in onCreate()

public void initTextView(){

Textview textView = (TextView) findViewById(R.id.textView); 


LinearLayout.LayoutParams  linearLayoutParams = new LinearLayout.LayoutParams(myWidth, myHeight);


textView.setLayoutParams(linearLayoutParams);

//This doesn't work
textView.setPadding(0, 100 ,0 , 0);

}

but if I comment out this line from above:

// textView.setLayoutParams(linearLayoutParams);

Then the setPadding() method does work.

Thanks in advance.


Solution

  • I don't believe there's anything wrong with the code, rather just not understanding what it's doing.... if your myHeight value is smaller than the padding, you're just simply not going to notice the effect.

    In the attached series of screenshots, the first screenshot is the default TextView containing a price (it has no layout params other than what's set in xml).

    In the 2nd screenshot I set the textview to the following (height=30, top padding = 100:

    LinearLayout.LayoutParams  linearLayoutParams = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, 30);
    textview.setLayoutParams(linearLayoutParams);
    textview.setPadding(0, 100, 0, 0);
    

    The text is there, the top padding is there, but it's all forced to "crop" to the set height of 30 (note I also lost all my original xml parameters (gravity, margins, etc) because setting LayoutParams cancels all of that and only applies whatever I set in those LayoutParams).

    In the 3rd screenshot I set the textview to the following (height=150, top padding = 100:

    LinearLayout.LayoutParams  linearLayoutParams = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, 150);
    textview.setLayoutParams(linearLayoutParams);
    textview.setPadding(0, 100, 0, 0);
    

    Voila! Since I've given the view ample height, it can fully display the text and the top padding (though again, I lost all my xml parameters).. If you go back to your source, try it out: replace myHeight with some fixed value (try at least 150) and see if things display as they should.

    enter image description here