Getting an android view button's width after setting it programatically - android

During my oncreate I have a button that is drawn. I come back and have it resized as part of the viewTreeObserver.OnGlobalLayoutListener() method. This works great. Within the same onGlobalLayouyListener method how can I come back and retrieve the width and height of the button. If I use btn.getwidth it returns the setting i have in my xml and not the value I just set. How can I retrieve the new width and height of the button.
mainlayout.getViewTreeObserver().addOnGlobalLayoutListener(
new ViewTreeObserver.OnGlobalLayoutListener() {
public void onGlobalLayout() {
Cyclebuttons(mainlayout);
getwidth();}
public void Cyclebuttons(ViewGroup parent) {
int btn2height= somenumber;
// set button width and height
ConstraintLayout.LayoutParams newLayoutParams = (ConstraintLayout.LayoutParams) btnx21.getLayoutParams();
newLayoutParams.width = btn2height;
newLayoutParams.height = btn2height;
btnx21.setLayoutParams(newLayoutParams);
}
public Void getwidth{
btnx21.getwidth();
}
thanks.

Didn't run the code, but the following might work:
public Void getwidth{
ConstraintLayout.LayoutParams newLayoutParams = (ConstraintLayout.LayoutParams) btnx21.getLayoutParams();
return newLayoutParams.width;
}

Related

Android LayoutParams not being updated properly

So I have a scroll view, and I need to adjust the height of my scroll view to make sure it stays above a modal pop-up view. I can't use a constraint layout because this modal pop-up view is not a child of the same view parent. So I'm trying to dynamically update my scroll views layout params so its height is small enough to not get hidden behind the modal pop-up.
The pop-up view height can change at points so I have a callback that returns the new height of the modal view anytime it changes. In that callback I adjust the scroll views height like so:
someModalView.onHeightChanged = { newViewHeight ->
Log.d("TESTHEIGHT", "PreHeight = ${scrollView.height}")
scrollView.layoutParams = FrameLayout.LayoutParams(scrollView.width, scrollView.height - newViewHeight)
scrollView.requestLayout()
Log.d("TESTHEIGHT", "PostHeight = ${scrollView.height}")
}
Unfortunately the above code seems to do nothing and in my logs I can see that the PreHeight prints the same height as the PostHeight. Any reason the views height isn't getting changed?
Also, I did debug it and make sure that newViewHeight is not 0, and it isn't, it's ~800
Ended up making it work by adding padding to the view rather than changing its height like so:
someModalView.onHeightChanged = { newViewHeight ->
scrollView.setPadding(0, 0, 0, newViewHeight)
}
This works exactly how i needed it to, however it doesn't really answer the question so I will just leave it in the answer for anyone else who it might help. But it would still be nice to know why changing the layout params wouldn't update the views height.
try to see it works for you
val params = scrollView.layoutParams;
params.height = scrollView.height - newViewHeight
scrollView.layoutParams = params
Once I needed to get the height of the softKeyboard to update my view:
public class MainActivity extends AppCompatActivity {
private ScrollView sView;
private int heightDiff;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
sView = findViewById(R.id.scrollView);
//Here we get the height of soft keyboard by observing changes of softKeyboard height.
sView.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
public void onGlobalLayout() {
heightDiff = sView.getRootView().getHeight() - sView.getHeight();
}
});
final EditText email = findViewById(R.id.eemail);
EditText firstName = findViewById(R.id.efirstname);
firstName.setOnFocusChangeListener(new View.OnFocusChangeListener() {
#Override
public void onFocusChange(View v, boolean hasFocus) {
if (!isVisibleWhileSoftKeyboardShowing(email) && hasFocus) {
sView.postDelayed(new Runnable() {
#Override
public void run() {
sView.smoothScrollBy(0, 200);
}
}, 500);
}
}
});
}
/**
* check if a view is currently visible in the screen or not
*
* #param view
* #return
*/
public boolean isVisibleWhileSoftKeyboardShowing(final View view) {
if (view == null) {
return false;
}
if (!view.isShown()) {
return false;
}
final Rect actualPosition = new Rect();
view.getGlobalVisibleRect(actualPosition);
final Rect screen = new Rect(0, 0, getScreenWidth(), getScreenHeight() - heightDiff);
return actualPosition.intersect(screen);
}
/**
* to get screen width
*
* #return
*/
public static int getScreenWidth() {
return Resources.getSystem().getDisplayMetrics().widthPixels;
}
/**
* to get screen height
*
* #return
*/
public static int getScreenHeight() {
return Resources.getSystem().getDisplayMetrics().heightPixels;
}
}
heightDiff is the height of softKeyboard. There was 2 edit texts. I wanted to scroll if softKeyboard hided the lower one. Hope this is similar to your case.

How do I change the dimensions of a View programmatically?

I just want an empty view with certain dimensions.
I declare the reference variable here:
public static View sv;
I instantiate the view in the onCreate method of my activity:
sv = new View(this);
and then attempt to set the dimensions right below it:
sv.setLayoutParams(new FrameLayout.LayoutParams(100, 100));
but when I call sv.getWidth() and sv.getHeight(), they still return 0
The height and width only will have value after of the OnCreate() and OnResume(). Try get height and width after this methods.
UPDATED
You can use a layout listener for this, depending on your goals. For example, in onCreate():
final View view = findViewById(android.R.id.view);
view.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
#Override
public void onGlobalLayout() {
view.getViewTreeObserver().removeOnGlobalLayoutListener(this);
//Now you can change the dimensions
}
});

Dynamically getting Height and Width of Layout

In my app I'm adding many views inside the Layout having below properties how shall i get the correct height of the layout at run time
LinearLayout ll = new LinearLayout(this);
ll.setLayoutParams(new LayoutParams(840,LayoutParams.WRAP_CONTENT));
ll.setOrientation(LinearLayout.VERTICAL);
ll.addView(view1);
ll.addView(view2);
ll.getHeight();
how to get Height of layout at that point consider adding of view1 and view2 , irrespective of my property(LayoutParams.WRAP_CONTENT), beacause it always return 0 to me?
Try this way,hope this will help you to solve your problem.
int width;
int height;
ll.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
#Override
public void onGlobalLayout() {
width = view.getMeasuredWidth();
height = view.getMeasuredHeight();
}
});
You can call
ll.post(new Runnable()
{
public void run()
{
ll.getHeight();
}
});
This will give you ll's height after adding the child views.

How to get the width and heigh of an imageview

I have this XML code:
<LinearLayout
android:id="#+id/linearLayoutInner"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#layout/gallery_image_background"
/>
Then this code:
LinearLayout linearLayoutInner = (LinearLayout) findViewById(R.id.linearLayoutInner);
ImageView imageView = new ImageView(thisActivityContext);
imageView.setImageResource(R.drawable.example);
imageView.setScaleType(ImageView.ScaleType.CENTER_INSIDE);
LayoutParams lp = new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);
imageView.setLayoutParams(lp);
linearLayoutInner.setGravity(Gravity.CENTER_HORIZONTAL|Gravity.CENTER_VERTICAL);
linearLayoutInner.addView(imageView);
I then call an own function that is meant to scale the bitmap image until one of the sides reach the edge (i.e. so if the original bitmat is twice as wide as tall, it will keep the proportion inside the imageview, something that is apparently not supported by any scaletype setting):
SharedCode.sharedUtilScaleImage(imageView);
And here comes the problem. That function needs to know the size of the view containing the bitmap drawable. if imageView behaves correctly, it should use MATCH_PARENT and hence give the width/height of the linearLayoutInner. However, the following code returns zero:
int heightParent = max(imageView.getLayoutParams().height, imageView.getHeight());
int widthParent = max(imageView.getLayoutParams().width, imageView.getWidth());
How do I solve this? And why am I returned 0 instead of the correct height/width?
You're probably calling the code too early, before the View's onMeasure() has been called. Until that happens, its size is unknown.
final ImageView iv....
ViewTreeObserver vto = iv.getViewTreeObserver();
vto.addOnGlobalLayoutListener(new OnGlobalLayoutListener() {
#Override
public void onGlobalLayout() {
//Measure
iv.getViewTreeObserver().removeGlobalOnLayoutListener(this);
}
});
final ImageView imageView = (ImageView )findViewById(R.id.image_test);
ViewTreeObserver vto = imageView.getViewTreeObserver();
vto.addOnGlobalLayoutListener(new OnGlobalLayoutListener() {
#Override
public void onGlobalLayout() {
imageView .getViewTreeObserver().removeGlobalOnLayoutListener(this);
imageView.getHeight(); // This will return actual height.
imageView.getWidth(); // This will return actual width.
}
});
Seem like you might be calling from onCreate(). u need to wait for activity window to attached and then call getWidth() andgetHeight() on imageView.You can try calling getWidth() and getHeight() from onWindowFocusChanged() method of your activity.
Edit
#Override
public void onWindowFocusChanged(boolean hasFocus){
int width=imageView.getWidth();
int height=imageView.getHeight();
}

Detect if some part of the view is NOT visible?

Is it possible to detect if some part of the view is not visible on the screen?
This is used in a situation that view's width/height is bigger that its parent's width/height.
EDIT
I get that the height of a view is 0. Does anyone knows why? I fetch the height in onCreate.
LinearLayout lin = (LinearLayout) findViewById(R.id.linear_layout);
final int layoutHeight = lin.getHeight();
Toast.makeText(this,"LinLay height: "+layoutHeight,Toast.LENGTH_SHORT).show();
...
button = (Button) findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
int displayTextWidth = textView.getWidth();
if (displayTextWidth <= layoutHeight) {
textView.setTextSize(textView.getTextSize() + 1);
}
}
});
You could get the view's width and height by calling View.getWidth() and View.getHeight(), then get the device dimensions by these means: How do I get a device's maximal width and height in android
Then compare the two, and if the view's bounds are larger than your device's bounds, then some parts of the view are not visible.
In response to comments:
textView.post( new Runnable() {
#Override
public void run() {
int displayTextWidth = textView.getWidth();
// Code that uses width here...
}
});

Categories

Resources