how to set width which is equal to another widget on android

前端 未结 7 425
走了就别回头了
走了就别回头了 2021-02-03 19:27

I need to draw a horizontal line below a text field such that the width of the line equals the text width (not the width of the full screen).

In my app I have a textview

7条回答
  •  野的像风
    2021-02-03 19:59

    If you're using a Layout other than a RelativeLayout, you can match the widths of your widgets programmatically, such as in this example:

    layout.xml:

    
    
        
    
        
    
    

    Notice that both text fields are both set to wrap_content.

    Main.java:

    TextView tv1 = (TextView) findViewById(R.id.text1);
    TextView tv2 = (TextView) findViewById(R.id.text2);
    
    if(tv1.getWidth() < tv2.getWidth())
        tv1.setWidth(tv2.getWidth());
    else
        tv2.setWidth(tv1.getWidth());
    

    If you have multiple widgets that you want to have a uniform width, just repeat the above code for the new element. For example, let's say there was a button I wanted to adjust the width to, to match the other elements:

    if(tv2.getWidth() < button)
        tv2.setWidth(button.getWidth());
    else
        button.setWidth(tv2.getWidth());
    

提交回复
热议问题