简体   繁体   中英

Programmatically set view width

I am developing an android app. There are six main long variables that are displayed on-screen at any time. These are continually incremented using a timer on a separate thread. The user can watch these variables increase on screen. Each of these variables has a maximum amount.

What I'd like to do is draw a 'progress bar' for each of these variables. At the moment, I am using a View with a solid red colour.

Please see below for prototype:

在此处输入图片说明

The red bar on the left would represent a variable that has reached it's maximum amount, whilst the others are empty and the bar has a width of 0, so is invisible. Each variable is placed in a RelativeLayout (which represents one 'section'), which is then placed in a LinearLayout . At a future point I may need to add/remove some - so the solution needs to not rely on hard-coded layout positionings.

My question is how can I programmaticaly set the width of these 'progress bar's in code, whilst not hard-coding the layout co-ordinates of any of the variables?

You should check http://developer.android.com/reference/android/widget/ProgressBar.html ProgressBar. It will ease you with displaying the progress.

In the case of LinearLayout (and any ViewGroup for that matter) you can generate your own LayoutParams programatically:

LayoutParams params = new LayoutParams(width,height) // in px
yourLinearLayout.setLayoutParams(params);

you will need to cast the LayoutParams to the according ViewGroup type.

The regular way would be to use the ProgressBar , but if you want to use your custom view, use this:

LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(withInPx, heightInPx);
yourView.setLayoutParams(lp);

This assumes you use LinearLayout , but you should edit that if you use a different layout (ie RelativeLayout )

The heightInPx will be fixed in your case, but the withInPx you can vary, according to the progress.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM