Not getting screen Height and widht in Android - android

I using both Using Activity or without Activity, Not getting both height and width in Android.Please correct me, What i am doing wrong.
Here With Activity:
public class LandPort extends Activity{
public final static int height = 0;
public final static int width = 0;
Context context;
DisplayMetrics displaymetrics = new DisplayMetrics();
public LandPort(Context context) {
this.context = context;
}
public int getHeight() {
getWindowManager().getDefaultDisplay().getMetrics(displaymetrics);
int height = displaymetrics.heightPixels;
return height;
}
public int getWidth() {
getWindowManager().getDefaultDisplay().getMetrics(displaymetrics);
int width = displaymetrics.widthPixels;
return width;
}
}
In MainActivity:
LandPort lp= new LandPort(getApplicationContext());
int height = lp.getHeight();
int width =lp.getWidth();
Getting height and width both 0;
Another Without Activity:
public class GetHeigthWidth {
public final static int height = 0;
public final static int widht = 0;
Context context;
WindowManager wm = (WindowManager) context
.getSystemService(Context.WINDOW_SERVICE);
Display display = wm.getDefaultDisplay();
public GetHeigthWidth(Context context) {
this.context = context;
}
public int getHeight() {
#SuppressWarnings("deprecation")
int height = display.getHeight();
return height;
}
public int getWidth() {
#SuppressWarnings("deprecation")
int widht = display.getWidth();
return widht;
}
}
From MainActivty:
GetHeigthWidth ghw= new GetHeigthWidth(getApplicationContext());
int height = ghw.getHeight();
int width =ghw.getWidth();
Aslo get Height and Width 0.
So, How to get Actual Height and width in this>

call your getHeight(); getWidth() stuff in
int height;
int width;
ViewTreeObserver vto = view.getViewTreeObserver();
vto.addOnGlobalLayoutListener(globalListner);
OnGlobalLayoutListener globalListner = new OnGlobalLayoutListener() {
#Override
public void onGlobalLayout() {
height = view.getHeight();
widht = view.getWidth();
}
});
and dont forget to remove that global listner at the End :)

Try this
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
DisplayMetrics displaymetrics = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(displaymetrics);
int height = displaymetrics.heightPixels;
getWindowManager().getDefaultDisplay().getMetrics(displaymetrics);
setContentView(R.layout.yourLayout);
}
you need to initialize your activity.
UPDATE
You need to do this:
import android.content.Context;
import android.view.Display;
import android.view.WindowManager;
public class GetHeigthWidth {
public final static int height = 0;
public final static int widht = 0;
Context context;
WindowManager wm;
Display display;
public GetHeigthWidth(Context context) {
this.context = context;
wm = (WindowManager) context
.getSystemService(Context.WINDOW_SERVICE);
display = wm.getDefaultDisplay();
}
public int getHeight() {
#SuppressWarnings("deprecation")
int height = display.getHeight();
return height;
}
public int getWidth() {
#SuppressWarnings("deprecation")
int widht = display.getWidth();
return widht;
}
}

DisplayMetrics displaymetrics = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(displaymetrics);
int height = displaymetrics.heightPixels;
int width = displaymetrics.widthPixels;

Related

Android get wrong screen size

I create android emulator with screen:
screen size: 7.5 inches
Resolution(width x height): 720x960
density: mdpi
And in Android virtual device manager it is shown xlarge screen size but in following code it returns Large screen size.
int screenLayout = context.getResources().getConfiguration().screenLayout;
screenLayout &= Configuration.SCREENLAYOUT_SIZE_MASK;
switch (screenLayout) {
case Configuration.SCREENLAYOUT_SIZE_SMALL:
return ScreenSize.SMALL;
case Configuration.SCREENLAYOUT_SIZE_NORMAL:
return ScreenSize.MEDIUM;
case Configuration.SCREENLAYOUT_SIZE_LARGE:
return ScreenSize.LARGE;
case Configuration.SCREENLAYOUT_SIZE_XLARGE:
return ScreenSize.XLARGE;
default:
}
You will be able to get screen Height and Width using:
WindowManager wm = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
Display display = wm.getDefaultDisplay();
DisplayMetrics metrics = new DisplayMetrics();
display.getMetrics(metrics);
int width = metrics.widthPixels;
int height = metrics.heightPixels;
Use Below code to get Height and Width of Android Phone Screen .
DisplayMetrics displayMetrics = getResources().getDisplayMetrics();
int height = displayMetrics.heightPixels;
int width= displayMetrics.widthPixels;
getscreen Height and width use
int screenWidth = getWindowManager().getDefaultDisplay().getWidth();
int screenHeight = getWindowManager().getDefaultDisplay().getHeight();
get layout Height use
int layoutHeight = Layout.getMeasuredHeight();
public static int getScreenWidth() {
return Resources.getSystem().getDisplayMetrics().widthPixels;
}
public static int getScreenHeight() {
return Resources.getSystem().getDisplayMetrics().heightPixels;
}
You can try this:
/**
* Get screen width
*
* #param context
* #return screen width
*/
public static int getScreenWidth(Context context)
{
WindowManager wm = (WindowManager) context
.getSystemService(Context.WINDOW_SERVICE);
DisplayMetrics outMetrics = new DisplayMetrics();
wm.getDefaultDisplay().getMetrics(outMetrics);
return outMetrics.widthPixels;
}
/**
* Get screen height
*
* #param context
* #return screen height
*/
public static int getScreenHeight(Context context)
{
WindowManager wm = (WindowManager) context
.getSystemService(Context.WINDOW_SERVICE);
DisplayMetrics outMetrics = new DisplayMetrics();
wm.getDefaultDisplay().getMetrics(outMetrics);
return outMetrics.heightPixels;
}

StaggeredGridLayoutManager make auto_fit columns

How i can make StaggeredGridLayoutManager auto_fit with all screens size , set number of columns automatically
recyclerViewadapter = new RecyclerViewAdapter(GetDataAdapter1, this);
StaggeredGridLayoutManager layoutManager = new StaggeredGridLayoutManager(3, StaggeredGridLayoutManager.VERTICAL);
recyclerView.setLayoutManager(layoutManager);
recyclerView.setAdapter(recyclerViewadapter);
If your items are at the same width, you can do this:
mRecyclerView.getViewTreeObserver().addOnGlobalLayoutListener(
new ViewTreeObserver.OnGlobalLayoutListener() {
#Override
public void onGlobalLayout() {
mRecyclerView.getViewTreeObserver().removeOnGLobalLayoutListener(this);
int viewWidth = mRecyclerView.getMeasuredWidth();
float cardViewWidth = getActivity().getResources().getDimension(R.dimen.cardview_layout_width);
int newSpanCount = (int) Math.floor(viewWidth / cardViewWidth);
mLayoutManager.setSpanCount(newSpanCount);
mLayoutManager.requestLayout();
}
});
Create help class for getting sizes.
public class GetSize {
public static int getColumnCount(Context context, int dp) {
if ((double) (getScreenWidth(context)/getPointOfDp(context, dp)) <= 1) return 1;
else return getScreenWidth(context)/getPointOfDp(context, dp);
}
public static int getScreenWidth(Context context){
WindowManager wm = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
Display display = wm.getDefaultDisplay();
Point point = new Point();
display.getSize(point);
return point.x; //Screen width
}
private static int getPointOfDp(Context context, int dp) { //Convert from dp to screen dots
return (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dp, context.getResources().getDisplayMetrics());
}
}
For get a column count need set some minimal width of your item.
int columnCount = GetSize.getColumnCount(context, 288);
layoutManager = new StaggeredGridLayoutManager(columnCount, StaggeredGridLayoutManager.VERTICAL);
recyclerView.setLayoutManager(layoutManager);
Try this
StaggeredGridLayoutManager layoutManager = new StaggeredGridLayoutManager(getSpan(), StaggeredGridLayoutManager.VERTICAL);
public int getSpan() {
int orientation = getScreenOrientation(getActivity());
if (isTV(getActivity())) return 4;
if (isTablet(getActivity()))
return orientation == Configuration.ORIENTATION_PORTRAIT ? 2 : 3;
return orientation == Configuration.ORIENTATION_PORTRAIT ? 2 : 3;
}
public static boolean isTV(Context context) {
return Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB_MR2 && ((UiModeManager) context
.getSystemService(Context.UI_MODE_SERVICE))
.getCurrentModeType() == Configuration.UI_MODE_TYPE_TELEVISION;
}
public static int getScreenOrientation(Context context) {
return context.getResources().getDisplayMetrics().widthPixels <
context.getResources().getDisplayMetrics().heightPixels ?
Configuration.ORIENTATION_PORTRAIT : Configuration.ORIENTATION_LANDSCAPE;
}
public static boolean isTablet(Context context) {
return (context.getResources().getConfiguration().screenLayout & Configuration.SCREENLAYOUT_SIZE_MASK) >= Configuration.SCREENLAYOUT_SIZE_LARGE;
}

A custom HorizontalScrollView,the method smoothScrollTo doesn't work

I have a custom HorizontalScrollView.But inside the class,the method smoothScrollTo doesn't work.The codes below is mine.
public class MyHorizontalScrollView extends HorizontalScrollView {
private int flagPosition;
private int scrollX;
private int windowWidth;
public MyHorizontalScrollView(Context context) {
super(context);
WindowManager manager = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
DisplayMetrics outMetrics = new DisplayMetrics();
manager.getDefaultDisplay().getMetrics(outMetrics);
windowWidth = outMetrics.widthPixels;
flagPosition = windowWidth / 2;
}
public MyHorizontalScrollView(Context context, AttributeSet attrs) {
super(context, attrs);
WindowManager manager = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
DisplayMetrics outMetrics = new DisplayMetrics();
manager.getDefaultDisplay().getMetrics(outMetrics);
windowWidth = outMetrics.widthPixels;
flagPosition = windowWidth / 2;
}
public MyHorizontalScrollView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
WindowManager manager = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
DisplayMetrics outMetrics = new DisplayMetrics();
manager.getDefaultDisplay().getMetrics(outMetrics);
windowWidth = outMetrics.widthPixels;
flagPosition = windowWidth / 2;
}
#Override
public void setSmoothScrollingEnabled(boolean smoothScrollingEnabled) {
super.setSmoothScrollingEnabled(true);
}
#Override
public boolean onTouchEvent(MotionEvent ev) {
int action = ev.getAction();
switch (action) {
case MotionEvent.ACTION_DOWN:
break;
case MotionEvent.ACTION_MOVE:
scrollX = getScrollX();
break;
case MotionEvent.ACTION_UP:
scroll();
break;
}
return super.onTouchEvent(ev);
}
private void scroll() {
if (scrollX <= flagPosition/2) {
smoothScrollTo(0, 0);
} else{
smoothScrollTo(flagPosition, 0);
}
}
#Override
protected void onScrollChanged(int l, int t, int oldl, int oldt) {
scrollX = getScrollX();
Log.v("my", "myscroll======+++++++onscrollchange" + scrollX);
}
}
I want a result that,I scroll the HorizontalScrollView,when I scroll to a range,then uplift my finger,the HorizontalScrollView will scroll to a specific position automaticly.
This is my code.Inside the method scroll(),I toggle smoothScrollTo.It doesn't work.But the method scrollTo worked.I don't know why.
I put the codes inside the class:
private Runnable run = new Runnable() {
#Override
public void run() {
if (scrollX <= flagPosition / 2) {
MyHorizontalScrollView.this.smoothScrollTo(0, 0);
} else {
MyHorizontalScrollView.this.smoothScrollTo(flagPosition, 0);
}
}
};
#Override
public boolean post(Runnable action) {
return super.post(action);
}
Then replace the method smoothScrollTo with post().And I realize the effect.

How to animate & control Android PreferenceFragment screens?

I have a PreferenceFragment whose contents are defined in XML. These contents include a child PreferenceScreen. When I click on the PreferenceScreen, the new screen is rendered successfully, but it has no animation (it just shows up on screen, even before the Material ripple is finished on Lollipop devices).
Even worse, if I had any complex layout going on (for example, the PreferenceFragment was in a tab on one side of the screen) that layout is blown away and replaced with a full-screen fragment.
I suspect that if I find the callback or event that occurs when a PreferenceScreen is clicked, I can solve both problems, but I don't really know where to start.
I did this for a slide in right-to-left animation of the PreferenceFragment...
I extended the PreferenceFragment and overridden the onCreateView() like this:
#Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = super.onCreateView(inflater, container, savedInstanceState);
AnimRelativeLayout animRelativeLayout = new AnimRelativeLayout(getActivity());
RelativeLayout.LayoutParams layoutParams = new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
animRelativeLayout.setLayoutParams(layoutParams);
animRelativeLayout.addView(view);
return animRelativeLayout;
}
where AnimRelativeLayout.java is
public class AnimRelativeLayout extends RelativeLayout {
private IMovementListener mMovementListener;
public AnimRelativeLayout(Context context) {
super(context);
this.initMembers();
}
public AnimRelativeLayout(Context context, AttributeSet attrs) {
super(context, attrs);
this.initMembers();
}
public AnimRelativeLayout(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
this.initMembers();
}
private void initMembers() {
this.mMovementListener = new SimpleMovementListener();
}
public float getXFraction() {
final WindowManager wm = (WindowManager) getContext().getSystemService(Context.WINDOW_SERVICE);
Display display = wm.getDefaultDisplay();
Point size = new Point();
display.getSize(size);
int width = size.x;
return (width == 0) ? 0 : getX() / (float) width;
}
public void setXFraction(float xFraction) {
final WindowManager wm = (WindowManager) getContext().getSystemService(Context.WINDOW_SERVICE);
Display display = wm.getDefaultDisplay();
Point size = new Point();
display.getSize(size);
int width = size.x;
this.mMovementListener.onSetXFraction(xFraction);
setX((width > 0) ? (xFraction * width) : 0);
}
public float getYFraction() {
final WindowManager wm = (WindowManager) getContext().getSystemService(Context.WINDOW_SERVICE);
Display display = wm.getDefaultDisplay();
Point size = new Point();
display.getSize(size);
int height = size.y;
return (height == 0) ? 0 : getY() / (float) height;
}
public void setYFraction(float yFraction) {
final WindowManager wm = (WindowManager) getContext().getSystemService(Context.WINDOW_SERVICE);
Display display = wm.getDefaultDisplay();
Point size = new Point();
display.getSize(size);
int height = size.y;
this.mMovementListener.onSetYFraction(yFraction);
setY((height > 0) ? (yFraction * height) : 0);
}
public interface IMovementListener {
public void onSetXFraction(float pXFraction);
public void onSetYFraction(float pYFraction);
}
private class SimpleMovementListener implements IMovementListener {
#Override
public void onSetXFraction(float pXFraction) {
}
#Override
public void onSetYFraction(float pYFraction) {
}
}
and then did this:
pFragmentManager.beginTransaction()
.setCustomAnimations(
R.animator.slide_in_right_to_left, R.animator.slide_out_right_to_left,
R.animator.slide_in_left_to_right, R.animator.slide_out_left_to_right
)
.replace(R.id.fragment_container, fragment)
.commit();
and an example for R.animator.slide_in_right_to_left is:
<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android">
<objectAnimator xmlns:android="http://schemas.android.com/apk/res/android"
android:duration="300"
android:propertyName="xFraction"
android:valueFrom="1.0"
android:valueTo="0"
android:valueType="floatType"/>
</set>

Get Screen width and height on android 2.2

How I can get screen width and height for use this value on device with android version 2.2(API lv8).
I use this code:
public static Point Maximum(Context context)
{
WindowManager wm = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
Display display = wm.getDefaultDisplay();
int width = display.getWidth(); // deprecated
int height = display.getHeight(); // deprecated
Point temp=new Point();
return temp;
}
And when i want check by print Max point to textview:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
TextView txt= (TextView)findViewById(R.id.text1);
txt.setText(Math.Maximum(this).toString());
}
Point is (0,0). What problem?
Try this code. But this API is deprecated in the new SDK versions you can use this.
Display display = activity.getWindowManager().getDefaultDisplay();
int width = display.getWidth();
int height = display.getHeight();
Get Device Width and Height, return as point. Hope u like this.
public static Point Maximum(){
Display display = activity.getWindowManager().getDefaultDisplay();
int width = display.getWidth();
int height = display.getHeight();
Point temp=new Point();
temp.set(width, height);
return temp;
}
Try this code:
DisplayMetrics displaymetrics = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(displaymetrics);
int height = displaymetrics.heightPixels;
int width = displaymetrics.widthPixels;
Try this for getting your screen width. Similarly you can get screen height or can customize the same for returning both in a single function.
#SuppressWarnings("deprecation")
#SuppressLint("NewApi")
private int getScreenWidth() {
int width = 400;
int height = 600; // just intialising it to default value in case if there is any problem getting screen width
WindowManager wm = (WindowManager) activity // activity is the context if you are using this method in adapter. Otherwise in Activity you can simply ignore this
.getSystemService(Context.WINDOW_SERVICE);
Display display = wm.getDefaultDisplay();
if (android.os.Build.VERSION.SDK_INT >= 13) {
Point size = new Point();
display.getSize(size);
width = size.x;
height = size.y;
} else {
width = display.getWidth();
height= display.getHeight();
}
return width;//or height
}

Categories

Resources