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

前端 未结 7 421
走了就别回头了
走了就别回头了 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:46

    What Jave said is correct - and the easiest, but what if you're not using a RelativeLayout to contain the View's ?

    If you're customizing your UI within onCreate() then you'll find that obtaining the width from another widget will give you an incorrect result ! That's because the UI hasn't been set up yet.

    But you can still set up your UI within onCreate... simply run code that executes after the UI is set up. This is achieved through use of the View.post() command.

    The XML :

    
    
        
    
            

    Java code:

    private Button mButtonOne;
    private Button mButtonTwo;
    
    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
    
        // inflate UI
        setContentView(R.layout.activity_example);
    
        // get references to UI elements
        mButtonOne = (Button)findViewById(R.id.button_one);
        mButtonTwo = (Button)findViewById(R.id.button_two);
    
        // Make buttons the same size (i.e. Button1.width = Button2.width)
        if ((mButtonOne != null) && (mButtonTwo != null))
        {
            mButtonOne.post(new Runnable()
            {
                @Override
                public void run()
                {
                    mButtonOne.setWidth(mButtonTwo.getWidth());
                }
            });
        }
    }
    

    The result is that the Width of button_one will match the Width of button_two. This is a nicer look when the amount of text varies heavily between the two View's.

提交回复
热议问题