I have a segment Android code:
final int[] finalWidth = new int[1];
final ImageView iv = (ImageView)findViewById(R.id.imageView);
textView = (TextView)findViewById(R.id.textView);
ViewTreeObserver vto = iv.getViewTreeObserver();
vto.addOnPreDrawListener(new ViewTreeObserver.OnPreDrawListener() {
public boolean onPreDraw() {
iv.getViewTreeObserver().removeOnPreDrawListener(this);
finalWidth[0] = iv.getMeasuredWidth();
textView.setText(Integer.toString(finalWidth[0]));
return true;
}
});
imageView = (ImageView)findViewById(R.id.imageView);
imageView.getLayoutParam().height = 1.6*finalWidth[0];
but , ImageView is invisiable after the app was built. Help me ! thanks you!
Assuming that gifImageView is your imageView.
gifImageView.post(new Runnable() {
#Override
public void run() {
int __w = gifImageView.getWidth();
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(__w, (int)(1.6 * __w)); // Since you can not apply float height
gifImageView.setLayoutParams(params);
gifImageView.invalidate();
}
});
Hope this helps.
Related
I create programmatically few layouts and I need get width one of them, recalculate this value and change. All this action I do in onGlobalLayoutListener. But when I set a new width value, he doesnt change.
private RelativeLayout batteryContainer;
private LinearLayout batteryLeftSide;
private LinearLayout batteryRightSide;
public void drawBattery(){
handler.post(new Runnable() {
#Override
public void run() {
//Контейнер всієї батарейки
batteryContainer = new RelativeLayout(activity);
RelativeLayout.LayoutParams batteryContainerParams = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.MATCH_PARENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
batteryContainerParams.setMargins((int) convertDpToPixel(containerMarginLeft), (int) convertDpToPixel(containerMarginTop), (int) convertDpToPixel(containerMarginRight), (int) convertDpToPixel(containerMarginBottom));
if(layoutBelow != null){
batteryContainerParams.addRule(RelativeLayout.BELOW, layoutBelow.getId());
}
if(layoutAbove != null){
batteryContainerParams.addRule(RelativeLayout.ABOVE, layoutAbove.getId());
}
batteryContainer.setLayoutParams(batteryContainerParams);
batteryContainer.setBackgroundColor(Color.parseColor("#505050"));
batteryContainer.setId(containerId);
int leftWidth = 0;
int rightWidth = 0;
//Ліва частина батарейки
batteryLeftSide = new LinearLayout(activity);
batteryLeftSide.setOrientation(LinearLayout.HORIZONTAL);
RelativeLayout.LayoutParams batteryLeftSideParams = new RelativeLayout.LayoutParams((int)convertDpToPixel(leftWidth), (int)convertDpToPixel(sideHeight));
batteryLeftSideParams.addRule(RelativeLayout.ALIGN_PARENT_LEFT);
batteryLeftSide.setLayoutParams(batteryLeftSideParams);
batteryLeftSide.setBackgroundColor(Color.parseColor("#900000"));
batteryLeftSide.setId(leftSideId);
//Права частина батарейки
batteryRightSide = new LinearLayout(activity);
batteryRightSide.setOrientation(LinearLayout.HORIZONTAL);
RelativeLayout.LayoutParams batteryRightSideParams = new RelativeLayout.LayoutParams((int)convertDpToPixel(rightWidth), (int)convertDpToPixel(sideHeight));
batteryRightSideParams.addRule(RelativeLayout.RIGHT_OF, batteryLeftSide.getId());
batteryRightSide.setLayoutParams(batteryRightSideParams);
batteryRightSide.setBackgroundColor(Color.parseColor("#009900"));
batteryRightSide.setId(rightSideId);
//Додамо праві та ліві сторони в контейнер
batteryContainer.addView(batteryLeftSide);
batteryContainer.addView(batteryRightSide);
//Додамо контейнер в кореневий Layout на активності
rootLayout.addView(batteryContainer);
//Обчислення яка сторона батарейки займе 50%
ViewTreeObserver observer = rootLayout.getViewTreeObserver();
observer.addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
#Override
public void onGlobalLayout() {
rootLayout.getViewTreeObserver().removeOnGlobalLayoutListener(this);
int batteryContainerWidth = batteryContainer.getMeasuredWidth();
int halfPlace = batteryContainerWidth * 50 / 100;
trustFromMe = halfPlace;
if(trustToMe > trustFromMe){
batteryLeftSide.getLayoutParams().width = halfPlace;
}
if(trustToMe < trustFromMe){
batteryRightSide.getLayoutParams().width = halfPlace;
}
if(trustToMe == trustFromMe){
batteryLeftSide.getLayoutParams().width = halfPlace;
batteryRightSide.getLayoutParams().width = halfPlace;
}
}
});
//but width not change
}
});
}
Try adding this to the end of the GlobalLayoutListener:
rootLayout.requestLayout();
This should force the layout to redraw it's size. If this doesn't work you may want to try creating and setting new LayoutParams as well.
I want to get height of linear layout that is set to wrap content. but it is zero.
i try this codes:
final LinearLayout below= (LinearLayout) findViewById(R.id.below);
ViewTreeObserver vto = below.getViewTreeObserver();
vto.addOnGlobalLayoutListener(new OnGlobalLayoutListener() {
#Override
public void onGlobalLayout() {
width = below.getMeasuredWidth();
height = below.getMeasuredHeight();
}
});
and :
LinearLayout below= (LinearLayout) findViewById(R.id.below);
final int belowh=below.getHeight();
using code:
final LinearLayout below= (LinearLayout) findViewById(R.id.below);
ViewTreeObserver vto = below.getViewTreeObserver();
vto.addOnGlobalLayoutListener(new OnGlobalLayoutListener() {
#Override
public void onGlobalLayout() {
if(below.getMeasuredHeight()> 0){
this.below.getViewTreeObserver().removeGlobalOnLayoutListener(this);
int width = below.getMeasuredWidth();
int height = below.getMeasuredHeight();
}
}
})
;
click here to see
Try this code for getting layout width and height after your view is created
final LinearLayout below= (LinearLayout) findViewById(R.id.below);
below.post(new Runnable()
{
#Override
public void run()
{
Log.i("TAG", "Layout width :"+ below.getWidth());
Log.i("TAG", "Layout height :"+ below.getHeight());
}
});
Hope this help
Try this
final LinearLayout below= (LinearLayout) findViewById(R.id.below);
ViewTreeObserver vto = below.getViewTreeObserver();
vto.addOnGlobalLayoutListener(new OnGlobalLayoutListener() {
#Override
public void onGlobalLayout() {
if(below.getMeasuredHeight()> 0){
this.below.getViewTreeObserver().removeGlobalOnLayoutListener(this);
int width = below.getMeasuredWidth();
int height = below.getMeasuredHeight();
}
}
})
;
#coder android
If you still stack on this.... please see this. I think this will work perfectly.
The following code is found How to retrieve the dimensions of a view?
final TextView tv = (TextView)findViewById(R.id.image_test);
ViewTreeObserver vto = tv.getViewTreeObserver();
vto.addOnGlobalLayoutListener(new OnGlobalLayoutListener() {
#Override
public void onGlobalLayout() {
LayerDrawable ld = (LayerDrawable)tv.getBackground();
ld.setLayerInset(1, 0, tv.getHeight() / 2, 0, 0);
ViewTreeObserver obs = tv.getViewTreeObserver();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
obs.removeOnGlobalLayoutListener(this);
} else {
obs.removeGlobalOnLayoutListener(this);
}
}
});
I know this is kind of a duplicate but the answers for other question didn't help me. always my ImageView height returns zero. here is what I tried:
dart.getViewTreeObserver().addOnPreDrawListener(
new ViewTreeObserver.OnPreDrawListener() {
public boolean onPreDraw() {
int finalHeight = dart.getMeasuredHeight();
int finalWidth = dart.getMeasuredWidth();
Toast.makeText(MainActivity.this," "+finalHeight,Toast.LENGTH_SHORT).show();
return true;
}
});
ALSO -
#Override
public void onWindowFocusChanged(boolean hasFocus) {
super.onWindowFocusChanged(hasFocus);
height = dart.getHeight();
width = dart.getWidth();
Toast.makeText(MainActivity.this," "+height,Toast.LENGTH_SHORT).show();
}
And I also tried dart.getHeight() inside the onCreate but I understood it can't work. What can I do?
Add addonPreDrawListener to ViewTreeObserver and call dart.getViewTreeObserver().removeOnPreDrawListener(this); in your onPreDraw() method
ViewTreeObserver vto = iv.getViewTreeObserver();
vto.addOnPreDrawListener(new ViewTreeObserver.OnPreDrawListener() {
public boolean onPreDraw() {
dart.getViewTreeObserver().removeOnPreDrawListener(this);
finalHeight = dart.getMeasuredHeight();
finalWidth = dart.getMeasuredWidth();
Toast.makeText(MainActivity.this," "+finalHeight,Toast.LENGTH_SHORT).show();
return true;
}
});
I have TextView created programmatically, like that:
TextView mTextView = new TextView(getApplicationContext());
final LayoutParams params = new TableLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
((MarginLayoutParams) params).setMargins(8, 8, 0, 0);
mTextView.setText(mText);
mTextView.setLayoutParams(params);
mTextView.setPadding(2, 2, 2, 2);
mTextView.setBackground(getResources().getDrawable(R.drawable.note_corps));
tagMap.addView(mTextView);
textViewsWidth = mTextView.getWidth();
But mTextView.getWidth() always returns 0
And if I try:
mTextView.getLayoutParams().width
It returns the LayoutParams corresponding value in the LayoutParams class (-1 or -2)
How can I get the view's width ?
EDIT I need to do this here:
#Override
public void onPostExecute(Hashtable<String, Integer> hash){
final ScrollView tagMapScroll = (ScrollView) findViewById(R.id.tagMapScroll);
final LinearLayout tagMap = (LinearLayout) findViewById(R.id.tagMap);
final ArrayList<Integer> arr = new ArrayList<Integer>(hash.values());
final Enumeration<String> e = hash.keys();
int index = 0;
int textViewsWidth = 0;
while(e.hasMoreElements()){
final TextView tV = new TextView(getApplicationContext());
tV.setTextColor(Color.parseColor("#666666"));
tV.setText(Html.fromHtml(randomColor() + e.nextElement()));
tV.setTextSize(arr.get(index));
final LayoutParams params = new TableLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
((MarginLayoutParams) params).setMargins(8, 8, 0, 0);
tV.setLayoutParams(params);
tV.setPadding(2, 2, 2, 2);
tV.setBackground(getResources().getDrawable(R.drawable.note_corps));
tagMap.addView(tV);
textViewsWidth += tV.getWidth();
index++;
}
tagMapScroll.setVisibility(ScrollView.VISIBLE);
}
EDIT SOLUTION I used this from #androiduser's answer:
mTextView.measure(MeasureSpec.UNSPECIFIED, MeasureSpec.UNSPECIFIED);
int width = mTextView.getMeasuredWidth();
int height = mTextView.getMeasuredHeight();
Problem solved !
I used this solution:
yourView.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
#Override
public void onGlobalLayout() {
// Ensure you call it only once
yourView.getViewTreeObserver().removeOnGlobalLayoutListener(this);
// Here you can get the size :)
}
});
get this way:
tV.post(new Runnable() {
#Override
public void run() {
int width=tV.getMeasuredWidth();
}
});
those values are constant value for FILL_PARENT and WRAP_CONTENT. If you want to check the view size you can try this way:
tagMap.addView(mTextView);
tagMap.post(new Runnable() {
#Override
public void run() {
mTextView. getWidth();
}
});
you have to wait until android draws the TextView. This way you are posting a Runnable in the tagMap queue, that is executed, hopefully after the textview is draw (so it should be weight and height)
In this method you can get the width height of the view..
#Override
public void onWindowFocusChanged(boolean hasFocus) {
super.onWindowFocusChanged(hasFocus);
int width = mTextView.getWidth();
int height = mTextView.getHeight();
}
and define TextView mTextView as global
You have to use ViewTreeObserver class which is used to register listeners that can be notified of global changes in the view tree. Such global events include, but are not limited to, layout of the whole tree, beginning of the drawing pass, touch mode change.
In the Activity's onCreate mehotd put this:
ViewTreeObserver vto = mTextView.getViewTreeObserver();
vto.addOnGlobalLayoutListener(new OnGlobalLayoutListener() {
#Override
public void onGlobalLayout() {
mTextView.getViewTreeObserver().removeGlobalOnLayoutListener(this);
int viewWidth = mTextView.getMeasuredWidth();
}
});
I use custom CursorAdapter with custom items.
I need height of view to resize Bitmap from assets folder and set this resized bitmap to ImegeView in list item;
#Override
public void bindView(View view, final Context context, final Cursor cursor) {
final ViewHolder holder = (ViewHolder) view.getTag();
final int imgCol = cursor.getColumnIndex(TableOdelice.COLUMN_URL);
int titleCol = cursor.getColumnIndex(TableOdelice.COLUMN_TITRE);
final int themeCol = cursor.getColumnIndex(TableOdelice.COLUMN_THEME);
String tempPath = getPath(cursor.getString(themeCol), cursor.getString(imgCol));
final String path = tempPath.replace(".", "c.");
String[] arr = cursor.getString(titleCol).split("\\*");
holder.title.setText(arr[0]);
holder.subTitle.setText(arr[1]);
if (itemHeight > 0) {
showThumb(itemHeight, holder.img, path);
} else {
final ImageView v = holder.mainImage;
v.getViewTreeObserver().addOnGlobalLayoutListener(new OnGlobalLayoutListener() {
#Override
public void onGlobalLayout() {
itemHeight = v.getHeight();
showThumb(itemHeight, holder.img, path);
}
});
}
}
private void showThumb(int height, final ImageView iv, final String path) {
if (thumbs.containsKey(path)) {
iv.setImageBitmap(thumbs.get(path));
} else {
InputStream is = null;
try {
is = context.getAssets().open(path);
} catch (IOException e) {
Log.d("no file at path", path);
e.printStackTrace();
}
if (is != null) {
Bitmap btm = btmHelper.scaleToHeight(BitmapFactory.decodeStream(is);, height);
thumbs.put(path, btm);
iv.setImageBitmap(btm);
}
}
}
For getting view height I use OnGlobalLayoutListener() of view.
But it's very slow ...
Any ideas?
I find answer for my question.
Using this construction I get a correct width or height of view inside adapter for each view.
final ImageView v = holder.mainImage;
v.post(new Runnable() {
#Override
public void run() {
itemHeight = v.getHeight();
Log.d("Height", "" + itemHeight);
}
});
}
Maybe it will help somebody :)
Just give it a try may be it will be faster
v.getViewTreeObserver().addOnGlobalLayoutListener(new OnGlobalLayoutListener() {
#Override
public void onGlobalLayout() {
itemHeight = v.getHeight();
showThumb(itemHeight, holder.img, path);
v.getViewTreeObserver().removeGlobalOnLayoutListener( ActivityInsatance);
}
});
If you have top or bottom margins, a bug will appear. When you will scroll this listview, a height of each row will increase. In case of v.getViewTreeObserver().addOnGlobalLayoutListener it will grow infinitely. So, my solution follows.
holder.layout.post(new Runnable() {
#Override
public void run() {
int height = holder.layout.getMeasuredHeight(); // Total row height.
RelativeLayout.LayoutParams lp = (RelativeLayout.LayoutParams) holder.textView.getLayoutParams();
holder.textView.setHeight(height - lp.topMargin - lp.bottomMargin);
});
where holder.layout is a link to root RelativeLayout of an adapter's row.