I want to make number of rows in Gridview dynamic depending upon the screen size of the android phone. so i need height of the Gridview in onCreate() to count number of rows.(height / colums) here is a code snippet::
public class GridActivity extends Activity
{
GridView gridView;
GridAdapter adapter;'
public void onCreate(Bundle savedInstance state)
{
setContentView(R.layout.gridview);
gridView = (GridView) findViewById(R.id.grid);
adapter = new GridAdapter(this);
gridView.setAdapter(adapter);
int gridHeight = gridView.getMeasuredHeight();
Log.d("tag"," height :: " + gridHeight);
}
}
In log cat it shows -- height :: 0
I don't understand y it gives zero after properly inflating.
Is this a bug? Or I am missing something?
GridView would return 0 measuredheight and 0 height unless it is drawn to window, so you can not get height of GridVIew at the point, A workaround of your problem may be:
Add your Nth view to gridView by comparing total height of device with height of GridView occupied after n-1 views has been drawn to screen.
public void addNCompareHeight(View view)
{
ViewTreeObserver observer = grid.getViewTreeObserver();
observer.addOnGlobalLayoutListener(new OnGlobalLayoutListener() {
#Override
public void onGlobalLayout() {
//in here, place the code that requires you to know the dimensions.
//this will be called as the layout is finished, prior to displaying.
if(gridHeight<requiredHeight)
{
grid.addView(view);
addNCompareHeight(next);
}
}
}
I am not sure how you are going to relate your mobile screen size and GridView heigth. But here are the codes for finding out Screen resolution and GridView height.
1)To Find screen resolution do this in your onCreate(),
DisplayMetrics dm = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(dm);
int screen_width = dm.widthPixels;
int screen_height = dm.heightPixels;
2)To find gridView height you can use the below method,
#Override
public void onWindowFocusChanged(boolean hasFocus)
{
// TODO Auto-generated method stub
super.onWindowFocusChanged(hasFocus);
System.out.println("...111Height..."+gridview.getMeasuredWidth());
}
Related
I have created a custom ViewGroup ReadPage, and in activity I use it
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_test);
pager=(ReadPage)findViewById(R.id.readpage);
pager.addArticle("...");
}
While the addArticle need the view's width and height
public void addArticle(String s){
articles.add(new Article(s,getMeasuredWidth(),getMeasuredHeight()));
}
But the measurewidth and measureheight is 0 at that time.
So I want to know at which state the view will be measured so I can get the right value it show in screen.
This answer probably gives you what you need: https://stackoverflow.com/a/1016941/213528
You would maybe use it like this:
private int WIDTH;
private int HEIGHT;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_test);
Display display = getWindowManager().getDefaultDisplay();
Point size = new Point();
display.getSize(size);
WIDTH = size.x;
HEIGHT = size.y;
pager = (ReadPage)findViewById(R.id.readpage);
pager.addArticle("...");
}
// ...
public void addArticle(String s){
articles.add(new Article(s, WIDTH, HEIGHT));
}
Use ViewTreeObserver
viewToMeasure.getViewTreeObserver().addOnGlobalLayoutListener(new OnGlobalLayoutListener() {
#Override
public void onGlobalLayout() {
viewToMeasure.getViewTreeObserver().removeGlobalOnLayoutListener(this);
/* you can get the view's height and width here
using viewToMeasure.getWidth() and viewToMeasure.getHeight()
*/
}
});
Views are measured sometimes later, during a "measure pass". When View structure changes (due to adding , removing, updating a view), a measure and then a layout pass runs that re-calculates the View sizes and locations.
For example, you can set text data to a TextView any time, but the View itself decides how to display it, when it is ready to display it. The text warp etc is calculated then, and not while setting the text.
You should design the View displaying the Article to be similar. You can provide the data, but let View process and display it further when its onSizeChanged() is called. Views can also employ addOnLayoutChangeListener() to know when layout has been done.
I'm trying to make a app that allows you to drag shapes around. It works fine on smart phones, but not on my Acer a500 tablet
When I get the height by calling
ih=getWindowManager().getDefaultDisplay().getHeight()-25;
I get a value thats only 1/3 of what it should be, thus I can only drag the sahpes 1/3 the way down. If the tablet is horizonatl it goes 1/2 way down.
Why is this methed returning the wrong values for the height on my tablet??
public class cPlay extends cBase implements OnClickListener {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// setContentView(R.layout.play);
int w=getWindowManager().getDefaultDisplay().getWidth()-25;
int h=getWindowManager().getDefaultDisplay().getHeight()-25;
BallView ballView=new BallView(this,w,h);
setContentView(ballView);
} // end function
public void onClick(View v) {
finish();
} // end function
} // end class
Try this:
DisplayMetrics displaymetrics = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(displaymetrics);
int height = displaymetrics.heightPixels;
int Width = displaymetrics.widthPixels;
Methods getWidth() and getHeight() are deprecated in Display.
Try to use DisplayMetrics.
Also you might want to get the size of your view's container by calling getMeasuredWidth() and getMeasuredHeight() after onMeasure() was called to get more precise size of your view.
I have an Activity with a view hierarchy as follows:
<RelativeLayout>
<LinearLayout>
<GridLayout />
</LinearLayout>
</RelativeLayout>
The top RelativeLayout takes up the full screen while the LinearLayout takes up a subset of the screen. I'm trying to set the size of the children views of the GridLayout in such a way that with n rows and m columns the size of cells is directly related to the n,m values and the width and height of the LinearLayout.
So for example, I'm trying to get the cell width and height as follows:
int linearLayoutWidth = mLinearLayout.getMeasuredWidth();
int linearLayoutHeight = mLinearLayout.getMeasuredHeight();
...
int rows = mGridModel.getRows() + 1;
int columns = mGridModel.getColumns() + 1;
int cellWidth = (int) (linearLayoutWidth / columns);
int cellHeight = (int) (linearLayoutHeight / rows);
Unfortunately, mLinearLayout.getMeasuredWidth() does not return the correct size when the view is created. It always returns the actual device's screen width until the views have been fully laid out - in which case it is too late. I have already given my children cell views the size based on the initially completely incorrect values.
My question is - how do I know when the views have been FULLY laid out. I need to query for their correct or actual measured width/height.
setContentView() creates the views and theoretically lays them out. But they views are not guaranteed to be in their final correct locations/sizes yet.
You can add ViewObserver to any view, in this observer there is a callback method onGlobalLayout, invoked when Layout has been laid;
ViewTreeObserver observer = view.getViewTreeObserver();
observer.addOnGlobalLayoutListener(new OnGlobalLayoutListener() {
#Override
public void onGlobalLayout() {
//in here, place the code that requires you to know the dimensions.
//this will be called as the layout is finished, prior to displaying.
}
}
Extending jeet's answer, you can have your activity implement the listener, which leads to slightly nicer code.
public class MyActivity extends Activity implements ViewTreeObserver.OnGlobalLayoutListener {
#Override
protected void onCreate(Bundle savedInstanceState) {
...
view.getViewTreeObserver().addOnGlobalLayoutListener(this);
}
#Override
public void onGlobalLayout() {
...
}
}
I'm wondering how to measure the dimensions of a view. In my case it is aan Absolute Layout. I've read the answers concerning those questions but I still don't get it.
This is my code:
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
AbsoluteLayout layoutbase = (AbsoluteLayout) findViewById(R.id.layoutbase);
drawOval();
}
public void drawOval(){ //, int screenWidth, int screenHeight){
AbsoluteLayout layoutbase = (AbsoluteLayout) findViewById(R.id.layoutbase);
int screenWidth = layoutbase.getWidth();
int screenHeight = layoutbase.getHeight();
Log.i("MyActivity", "screenWidth: " + screenWidth + ", screenHeight: " +screenHeight);
Coordinates c = new Coordinates(BUTTONSIZE,screenWidth,screenHeight);
...some code ...
((ViewGroup) layoutbase ).addView(mybutton, new AbsoluteLayout.LayoutParams(BUTTONSIZE, BUTTONSIZE, c.mX, c.mY));
mybutton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
showText(mybutton);
}
});
}
public void showText(View button){
int x = findViewById(LAYOUT).getWidth();
int y = findViewById(LAYOUT).getHeight();
Toast message = Toast.makeText(this, "x: " + x , Toast.LENGTH_SHORT);
message.show();
}
The getWidth() command works great in showText() but it does not in drawOval(). I know it looks a bit different there but I also used the int x = findViewById(LAYOUT).getWidth(); version in drawOval(), and x/y are always 0. I don't really understand why there seems to be no width/height at that earlier point. Even if I actually draw a Button on the Absolute Layout, getWidth() returns 0. Oviously I want to measure the sizes in drawOval().
I think will help you.
LinearLayout headerLayout = (LinearLayout)findviewbyid(R.id.headerLayout);
ViewTreeObserver observer = headerLayout .getViewTreeObserver();
observer.addOnGlobalLayoutListener(new OnGlobalLayoutListener() {
#Override
public void onGlobalLayout() {
// TODO Auto-generated method stub
int headerLayoutHeight= headerLayout.getHeight();
int headerLayoutWidth = headerLayout.getWidth();
headerLayout .getViewTreeObserver().removeGlobalOnLayoutListener(
this);
}
});
}
getWidth() is giving you 0 because onCreate is called before layout actually happens. Due to views being able to have dynamic positions and sizes based on attributes or other elements (fill_parent for example) there's not a fixed size for any given view or layout. At runtime there is a point in time (actually it can happen repeatedly depending on many factors) where everything is actually measured and laid out. If you really need the height and width, you'll have to get them later as you've discovered.
This specially deal with Dimensions so
Display display = getWindowManager().getDefaultDisplay();
int width = display.getWidth();
int height = display.getHeight();
This may help you in managing dimensions.
Note: This returns the display dimensions in pixels - as expected. But the getWidth() and getHeight() methods are deprecated. Instead you can use:
Display display = getWindowManager().getDefaultDisplay();
Point size = new Point();
display.getSize(size);
int width = size.x;
int height = size.y;
as also Martin Koubek suggested.
If your goal is to simply draw an oval on the screen, then consider creating your own custom View rather than messing around with AbsoluteLayout. Your custom View must override onDraw(android.graphics.Canvas), which will be called when the view should render its content.
Here is some extremely simple sample code that might help get you started:
public class MainActivity extends Activity {
private final Paint mPaint = new Paint();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(new SampleView(this));
}
// create a nested custom view class that can draw an oval. if the
// "SampleView" is not specific to the Activity, put the class in
// a new file called "SampleView.java" and make the class public
// and non-static so that other Activities can use it.
private static class SampleView extends View {
public SampleView(Context context) {
super(context);
setFocusable(true);
}
#Override
protected void onDraw(Canvas canvas) {
canvas.drawColor(Color.CYAN);
// smoothen edges
mPaint.setAntiAlias(true);
mPaint.setColor(Color.RED);
mPaint.setStyle(Paint.Style.STROKE);
mPaint.setStrokeWidth(4.5f);
// set alpha value (opacity)
mPaint.setAlpha(0x80);
// draw oval on canvas
canvas.drawOval(new RectF(50, 50, 20, 40), mPaint);
}
}
}
This give you screen resolution:
WindowManager wm = (WindowManager)context.getSystemService(context.WINDOW_SERVICE);
Display display = wm.getDefaultDisplay();
Point outSize = new Point();
display.getSize(outSize);
kabuko's answer is correct, but could be a little more clear, so let me clarify.
getWidth() and getHeight() are (correctly) giving you 0 because they have not been drawn in the layout when you call them. try calling the two methods on the button after addView() (after the view has been drawn and is present in the layout) and see if that gives you the expected result.
See this post for more information.
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...
}
});