开发者

How to align text view with above widget?

开发者 https://www.devze.com 2023-04-10 04:40 出处:网络
My UI contains two elements: a button on top and a textview below the button. The width of the button is set to \"wrap_content\", so it will change its width when I set different text to the button in

My UI contains two elements: a button on top and a textview below the button. The width of the button is set to "wrap_content", so it will change its width when I set different text to the button in the run time. I want to always let the textview align with the button(has the same width), especially the UI is first loaded.

I tried to get width of the button in onGlobalLayout event and set the width of textview, but it seems not work. Can an开发者_开发知识库yone help me?

UPDATE:

I think I might have over simplified my problem. The real UI has lots of widgets (both button and textview in my question) generated by code. So I can't use XML to define them. And because the UI is not totally loaded, I can't use getWidth() the get the real width of the button when I align the text view.


I think you should use the Android LayoutParams.

http://developer.android.com/reference/android/view/ViewGroup.LayoutParams.html

In onCreate or in the code where your are setting the text to a button. After setting the text int button you should set the width on textview = width of button using the button's layout params.


Make this layout in XML, use RelativeLayout as container for Button and TextView.

Then for the TextView you would specify alignment:

android:layout_alignLeft="@+id/button1" 
android:layout_alignRight="@+id/button1"

thus both its left and right side is aligned to your button.

Note: you can make same also from java code using RelativeLayout.LayoutParams, but it's more complicated than using XML.


In case, you do like working in code, this is one sample regarding Button and TextView having same width:

public class MainActivity extends Activity {
    Button mButton;
    TextView mText;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);        

        mButton = (Button)findViewById(R.id.button);
        mText = (TextView)findViewById(R.id.text);

        updateUI();
    }

    public void updateUI() {
        int wButton = mButton.getWidth();
        int wText = mText.getWidth();

        if(wButton < wText) {
            mButton.setWidth(wText);
        } else {
            mText.setWidth(wButton);
        }
    }
}

Well, the drawback is you need to call updateUI() everytime you update the text of either control.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号