Setting width to wrap_content for TextView through code

后端 未结 6 1325
我在风中等你
我在风中等你 2020-12-25 09:24

Can anyone help me how to set the width of TextView to wrap_content through code and not from XML?

I am dynamically creating a TextVi

相关标签:
6条回答
  • 2020-12-25 09:40

    I think this code answer your question

    RelativeLayout.LayoutParams params = (RelativeLayout.LayoutParams) 
    holder.desc1.getLayoutParams();
    params.height = RelativeLayout.LayoutParams.WRAP_CONTENT;
    holder.desc1.setLayoutParams(params);
    
    0 讨论(0)
  • 2020-12-25 09:41

    I am posting android Java base multi line edittext.

    EditText editText = findViewById(R.id.editText);/* edittext access */
    
    ViewGroup.LayoutParams params  =  editText.getLayoutParams(); 
    params.height = ViewGroup.LayoutParams.WRAP_CONTENT;
    editText.setLayoutParams(params); /* Gives as much height for multi line*/
    
    editText.setSingleLine(false); /* Makes it Multi line */
    
    0 讨论(0)
  • 2020-12-25 09:48

    Solution for change TextView width to wrap content.

    textView.getLayoutParams().width = ViewGroup.LayoutParams.WRAP_CONTENT; 
    textView.requestLayout();  
    // Call requestLayout() for redraw your TextView when your TextView is already drawn (laid out) (eg: you update TextView width when click a Button). 
    // If your TextView is drawing you may not need requestLayout() (eg: you change TextView width inside onCreate()). However if you call it, it still working well => for easy: always use requestLayout()
    
    // Another useful example
    // textView.getLayoutParams().width = 200; // For change `TextView` width to 200 pixel
    
    0 讨论(0)
  • 2020-12-25 09:50

    There is another way to achieve same result. In case you need to set only one parameter, for example 'height':

    TextView textView = (TextView)findViewById(R.id.text_view);
    ViewGroup.LayoutParams params = textView.getLayoutParams();
    params.height = ViewGroup.LayoutParams.WRAP_CONTENT;
    textView.setLayoutParams(params);
    
    0 讨论(0)
  • 2020-12-25 10:04

    A little update on this post: if you are using ktx within your Android project, there is a little helper method that makes updating LayoutParams a lot easier.

    If you want to update e.g. only the width you can do that with the following line in Kotlin.

    tv.updateLayoutParams { width = WRAP_CONTENT }
    
    0 讨论(0)
  • 2020-12-25 10:05
    TextView pf = new TextView(context);
    pf.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
    

    For different layouts like ConstraintLayout and others, they have their own LayoutParams, like so:

    pf.setLayoutParams(new ConstraintLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT)); 
    

    or

    parentView.addView(pf, new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
    
    0 讨论(0)
提交回复
热议问题