0

i'am trying to develop an app where an item goes down and when you touch the screen rises, but I have two smarthphones and one is larger than the other and want the greater the speed at which the item is dropped as in the small. this is my class (no extends from Activity)

public class VistaJuego extends View{
Grafico item;
public VistaJuego(Context context, AttributeSet attrs) {
    super(context, attrs);

item = new Grafico(this, drawableFaba);
}
@Override
protected void onSizeChanged(int w, int h, int oldw, int oldh) {
    super.onSizeChanged(w, h, oldw, oldh);

    item.setPosX(w/2);
    item.setPosY(h/2);
    item.setHeightCanvas(h);
    item.setWidthCanvas(w);
    height=h;
    width=w;


    if(h<=800){
        item.setIncreaseY(7);//increase speed posY x 7
    }else{
        item.setIncreaseY(15);//increase speed posY x 7
    }
}

And i can't use DisplayMetrics because this class is not extends Activity. Any idea?? Pleaseee

Sergio Chuky
  • 51
  • 10

3 Answers3

1

You can still use DisplayMetrics. A simple way is to pass in a Context. But since this is a VIew, you don't even need to do that- it's done for you. Use getContext() to get the Activity, then you can call any function on activity you need- such as getContext().getResources().getDisplayMetrics();

Gabe Sechan
  • 90,003
  • 9
  • 87
  • 127
1

Metrics in pixels.

Display display = getWindowManager().getDefaultDisplay();
Point size = new Point();
display.getSize(size);
int width = size.x;
int height = size.y;

if you're not in an Activity you can get the default Display via WINDOW_SERVICE:

WindowManager wm = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
Display display = wm.getDefaultDisplay();
Gilberto Ibarra
  • 2,849
  • 2
  • 27
  • 38
  • yes I understand and your code works but when i run my app in HTC one M8 (largest) the item fall with the same speed, very low, while that in the Huawei Ascend (small) it fall very fast... – Sergio Chuky May 14 '15 at 20:25
1

You can get the height in pixels by getting the default display from the window manager. As you don't have access to an activity from your class, you should get it from the WINDOW_SERVICE:

WindowManager wm = (WindowManager)context.getSystemService(Context.WINDOW_SERVICE);
Display display = wm.getDefaultDisplay();
Point size = new Point();
display.getSize(size);
int height = size.y;

As described in the top answer for this question.

Community
  • 1
  • 1
Gabriel Huff
  • 743
  • 1
  • 6
  • 18