2012-04-16 13 views
28

Estoy desarrollando una aplicación en la que tengo que hacer que nuestra aplicación se adapte a todos los dispositivos, tanto para tabletas como para dispositivos móviles con Android. Ahora quiero obtener el alto y el ancho del dispositivo en tiempo de ejecución e implementarlo en mi código para que mi aplicación funcione tanto en horizontal como en vertical.¿Cómo obtener la altura y el ancho del dispositivo en tiempo de ejecución?

Mi archivo XML es:

<?xml version="1.0" encoding="utf-8"?> 
<LinearLayout 
    xmlns:android="http://schemas.android.com/apk/res/android" 
    android:layout_width="match_parent" 
    android:layout_height="match_parent" 
    android:layout_weight="2" android:orientation="vertical"> 

    <LinearLayout android:id="@+id/linearLayout1" android:layout_height="match_parent" 
    android:orientation="horizontal" android:layout_width="match_parent" 
    android:layout_weight="1"> 

     <LinearLayout android:id="@+id/linearLayout1" android:layout_height="match_parent" 
     android:orientation="vertical" android:layout_width="match_parent" 
     android:layout_weight="1" android:weightSum="100"> 
      <TextView android:id="@+id/letter1" android:gravity="center" android:layout_width="fill_parent" android:layout_height="wrap_content" android:layout_weight="60"></TextView> 
      <TextView android:id="@+id/letter2" android:gravity="center" android:layout_width="fill_parent" android:layout_height="wrap_content" android:layout_weight="20"></TextView> 
      <TextView android:id="@+id/letter3" android:gravity="center" android:layout_width="fill_parent" android:layout_height="wrap_content" android:layout_weight="20"></TextView> 
     </LinearLayout> 

     <LinearLayout android:id="@+id/linearLayout1" android:layout_height="match_parent" 
     android:gravity="center" 
     android:orientation="horizontal" android:layout_width="match_parent" 
     android:layout_weight="1"> 
      <ImageView android:id="@+id/imag" 
      android:gravity="center" 
      android:scaleType = "fitCenter" 
      android:layout_height="fill_parent" 
      android:layout_width="fill_parent" 
      android:layout_gravity="center"> 
     </ImageView> 

     </LinearLayout> 

    </LinearLayout> 


     <LinearLayout android:layout_gravity="bottom" 
     android:id="@+id/linearLayout2" 
     android:layout_height="wrap_content" android:orientation="horizontal" android:layout_width="match_parent"> 
      <Button android:id="@+id/previous" android:layout_width="wrap_content" android:layout_weight="1" android:text="Previous" android:layout_height="wrap_content" ></Button> 
      <Button android:id="@+id/practice" android:layout_width="wrap_content" android:layout_weight="1" android:text="Practice" android:layout_height="wrap_content" android:onClick="onClick"></Button> 
      <Button android:id="@+id/home" android:layout_width="wrap_content" android:layout_weight="1" android:text="Home" android:layout_height="wrap_content"></Button> 
      <Button android:id="@+id/spell" android:layout_width="wrap_content" android:layout_weight="1" android:text="Spell" android:layout_height="wrap_content" android:onClick="Content"></Button> 
      <Button android:id="@+id/next" android:layout_width="wrap_content" android:layout_weight="1" android:text="Next" android:layout_height="wrap_content" android:onClick="Content"></Button> 


     </LinearLayout> 

</LinearLayout> 

Mi archivo Java es:

package com.android; 

import android.app.Activity; 
import android.content.Intent; 
import android.graphics.Bitmap; 
import android.graphics.BitmapFactory; 
import android.graphics.Typeface; 
import android.media.MediaPlayer; 
import android.os.Bundle; 
import android.view.MotionEvent; 
import android.view.View; 
import android.view.View.OnClickListener; 
import android.widget.Button; 
import android.widget.ImageView; 
import android.widget.TextView; 
import android.widget.Toast; 

import com.android.SimpleGestureFilter.SimpleGestureListener; 

public class MySwara extends Activity implements SimpleGestureListener { 


    private SimpleGestureFilter detector; 
    private static int counter=-1; 
    private String[] mBtn1 ={"C","D","E","F","G","H","IÄ","J","K","L","M","N","O","CA","CB"}; 
    private TextView txtLetter; 
    private ImageView imgLetter; 

    private int[] imgArr={R.drawable.w1,R.drawable.w2,R.drawable.w3,R.drawable.w4,R.drawable.w5,R.drawable.w6,R.drawable.w7,R.drawable.w8,R.drawable.w9,R.drawable.w10,R.drawable.w11,R.drawable.w12, 
          R.drawable.w13,R.drawable.w14,R.drawable.w15}; 
    private TextView txtKannada; 
    private String[] mBtn2 = {"CgÀ¸À","DªÉÄ","E°","F±À","GqÀ","Hl","IĶ","J¯É","Kr","LzÀÄ","M¯É","N¯É","OµÀzsÀ", 
      "CAUÀr","CB"}; 
    private String[] mBtn3 = {"ARASA","AME","ILI","ISA","UDA","UTA","RUSHI","ELE","EDI","AIDU","oLE","OLE","AUSHADA", 
      "ANGADI","AHA"}; 
    private TextView txtEnglish; 

    private int[] mAudio = {R.raw.a,R.raw.b,R.raw.c,R.raw.d,R.raw.e,R.raw.f,R.raw.g,R.raw.h,R.raw.i,R.raw.j, 
      R.raw.k,R.raw.l,R.raw.m,R.raw.n,R.raw.o}; 
    protected MediaPlayer mp; 
    @Override 
    protected void onCreate(Bundle savedInstanceState) { 
     // TODO Auto-generated method stub 
      super.onCreate(savedInstanceState); 
      setContentView(R.layout.content); 

      detector = new SimpleGestureFilter(this,this); 
      if(counter == -1) 
       counter =getIntent().getExtras().getInt("POSITION"); 
      Typeface tf = Typeface.createFromAsset(getBaseContext().getAssets(), "fonts/brhknd.ttf"); 
      txtLetter = (TextView)findViewById(R.id.letter1); 
      txtKannada = (TextView)findViewById(R.id.letter2); 
      txtEnglish = (TextView)findViewById(R.id.letter3); 
      imgLetter = (ImageView)findViewById(R.id.imag); 
      txtLetter.setTypeface(tf);  
      txtLetter.setText(mBtn1[counter]); 
      //txtLetter.setTextSize(350); 

      Bitmap bm = BitmapFactory.decodeResource(getResources(), imgArr[counter]); 
      imgLetter.setImageBitmap(bm); 

      txtKannada.setTypeface(tf); 
      txtKannada.setText(mBtn2[counter]); 
      //txtKannada.setTextSize(100); 

      txtEnglish.setText(mBtn3[counter]); 
      //txtEnglish.setTextSize(50); 



      Button btnNext = (Button)findViewById(R.id.next); 
      btnNext.setOnClickListener(new OnClickListener() { 

       @Override 
       public void onClick(View v) { 


        if(counter<imgArr.length-1) 
         counter++; 
        changeContent(); 
       } 
      }); 

      Button mPlay = (Button)findViewById(R.id.spell); 
      mPlay.setOnClickListener(new OnClickListener() { 

       @Override 
       public void onClick(View v) { 
        mp = MediaPlayer.create(MySwara.this, mAudio[counter]); 
        mp.start(); 

       } 
      }); 


      Button btnPrvs = (Button)findViewById(R.id.previous); 
      btnPrvs.setOnClickListener(new OnClickListener() { 

       @Override 
       public void onClick(View v) { 


        if(counter>0) 
         counter--; 
        changeContent(); 
       } 
      }); 


      Button btnPractice = (Button)findViewById(R.id.practice); 
      btnPractice.setOnClickListener(new OnClickListener() { 

       @Override 
       public void onClick(View v) { 
        Intent intent = new Intent(MySwara.this,DrawingActivity.class); 
        startActivity(intent); 

       } 
      }); 
      Button btnHome = (Button)findViewById(R.id.home); 
      btnHome.setOnClickListener(new OnClickListener() { 

       @Override 
       public void onClick(View v) { 
        Intent intent = new Intent(MySwara.this,mainClass.class); 
        startActivity(intent); 

       } 
      }); 
    } 



    public void changeContent() 
    { 

     txtLetter.setText(mBtn1[counter]); 
     txtKannada.setText(mBtn2[counter]); 
     txtEnglish.setText(mBtn3[counter]); 
     //imgLetter.setBackgroundResource(imgArr[counter]); 
     Bitmap bm = BitmapFactory.decodeResource(getResources(), imgArr[counter]); 
     imgLetter.setImageBitmap(bm); 

    } 


@Override 
     public boolean dispatchTouchEvent(MotionEvent me){ 
      this.detector.onTouchEvent(me); 
     return super.dispatchTouchEvent(me); 
     } 
    @Override 
    public void onSwipe(int direction) { 
     String str = ""; 

     switch (direction) { 

     case SimpleGestureFilter.SWIPE_RIGHT : str = "Swipe Right"; 

               if(counter>0) 
                counter--; 
                changeContent(); 
               break; 
     case SimpleGestureFilter.SWIPE_LEFT : str = "Swipe Left"; 
              if(counter<imgArr.length-1) 
               counter++; 
               changeContent(); 
                break; 

     } 

    } 



    @Override 
    public void onDoubleTap() { 
     // TODO Auto-generated method stub 

    } 


    } 
+0

http://stackoverflow.com/questions/2902640/android-get-the-screen-resolution-pixels-as-integer-values ​​comprueba esto ... – RobinHood

+1

esto te ayudará. [link] [1] [1]: http: // stackoverflow.com/questions/1016896/android-how-to-get-screen-dimensions – Noundla

+3

usted debería aceptar el anser – stinepike

Respuesta

10

En el onCreate de su actividad que puede hacer

mScreenWidth = getActivity().getWindowManager().getDefaultDisplay().getWidth(); 

mScreenHeight = getActivity().getWindowManager().getDefaultDisplay().getHeight(); 

y luego utilizar estas variables para acceder a la altura y ancho del dispositivo

+0

Entonces, ¿cómo debería usarlo en el código? – user1271118

+3

si puedo ser franco aquí, esa pregunta no tiene sentido. querías los valores ¿Para qué lo quieres usar? – josephus

63
Display mDisplay = activity.getWindowManager().getDefaultDisplay(); 
final int width = mDisplay.getWidth(); 
final int height = mDisplay.getHeight(); 

De esta forma puede obtener el tamaño de la pantalla.

Dado que esta API está privada en las nuevas versiones de SDK, puede usar esto.

DisplayMetrics displayMetrics = context.getResources().getDisplayMetrics(); 
int width = displayMetrics.widthPixels; 
int height = displayMetrics.heightPixels; 
+5

GetWidth y getHeight de la pantalla están en desuso. – emrahgunduz

+2

getWidth() y getHeight() están en desuso en el nivel de la API 13. En su lugar use Display.getSize() como este, 'Display display = getWindowManager(). GetDefaultDisplay(); Tamaño de punto = nuevo Punto(); if (Build.VERSION.SDK_INT> = Build.VERSION_CODES.JELLY_BEAN_MR1) { display.getSize (size); int width = size.x; int height = size.y; } ' Los valores devueltos están en píxeles. – luckylukein

22

En un ámbito Actividad hacer:

DisplayMetrics dm = new DisplayMetrics(); 
getWindowManager().getDefaultDisplay().getMetrics(dm); 
int w = dm.widthPixels; // etc... 
3

esta es la forma de obtener las dimensiones de la pantalla disponibles. Esto no le proporcionará el tamaño de píxel bruto, sino el espacio disponible de su ventana/actividad.

Point outSize = new Point(); 
    getWindowManager().getDefaultDisplay().getSize(outSize); 

También puede tener diferentes archivos de diseño xml para paisaje y retrato. Ponga su xml para retrato en res/layout-port. El diseño para el paisaje se puede poner en res/layout-land. Usted debe leer cómo administra resources

2

androide Puede obtener información relacionada con toda la pantalla utilizando las métricas de clase de visualización http://developer.android.com/reference/android/util/DisplayMetrics.html

que se requieren

DisplayMetrics metrics = new DisplayMetrics(); 
getWindowManager().getDefaultDisplay().getMetrics(metrics); 

Después de esto toda la información requerida estará presente en tu objeto de métricas

La otra opción es llamar

getActivity().getWindowManager().getDefaultDisplay().getWidth() 
getActivity().getWindowManager().getDefaultDisplay().getHeight() 
2

no voy a decir cómo obtener las dimensiones de la pantalla, como todo el mundo aquí que ya hizo. Le indico un link de la guía de desarrollo de desarrolladores de Android, que debe enseñarle a diseñar y desarrollar dispositivos de diferentes tamaños de pantalla.

Después de leer, vuelve y cuéntanos otra vez que todavía deseas obtener el ancho y el alto de la pantalla.

Cuestiones relacionadas