2015-02-17 5 views
7

Provo a creare un metodo che restituisca la definizione dello schermo dipendente da se il dispositivo è un palmare o un tablet.Come utilizzare @ ActivityInfo.ScreenOrientation

public int getScreenOrientation(boolean isTablet){ 
    if(isTablet){ 
     return ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE; 
    } else { 
     return ActivityInfo.SCREEN_ORIENTATION_PORTRAIT; 
    } 
} 

Ma quando uso setRequestedOrientation(getScreenOrientation)); ottengo un panno errori Must be one of: ActivityInfo.SCREEN_ORIENTATION_......... cui posso reprimere, ma che non sembrano codice pulito.

Quindi ho trovato che ilutilizza l'annotazione @ActivityInfo.ScreenOrientation. Così ho cercato di usare io stesso:

@ActivityInfo.ScreenOrientation 
public int getScreenOrientation(boolean isTablet){ 
    . 
    . 
    . 
} 

Ma l'IDE mi dà un errore che indica che l'annotazione @ActivityInfo.ScreenOrientation non è stato trovato. Ma è dichiarato pubblico nella fonte ufficiale di Android.

+1

Sono nella stessa situazione e io davvero non capisco perché mi non posso usare '@ ActivityInfo.ScreemOrientation' ... – tbruyelle

risposta

9

inserire il seguente commento sopra l'istruzione fastidiosa in cui viene attivato il controllo costante magica per @IntDef and @StringDef annotation, ad esempio:

//noinspection ResourceType 
setRequestOrientation(lock); 
+1

Non sono il più grande fan di sopprimere l'errore ma funziona ed è meglio che scrivere 5 linee di codice in ogni attività. Grazie! – Altoyyr

0

Provare invece l'annotazione @IntegerRes. Questo dovrebbe funzionare bene per te dato che stai restituendo un attributo di risorsa intero da android.R.attr.

https://developer.android.com/reference/android/support/annotation/IntegerRes.html http://developer.android.com/reference/android/R.attr.html#screenOrientation

L'esempio seguente sta lavorando per me senza errori IDE o avvisi.

@IntegerRes 
public static int getScreenOrientationPref() { 
    if(sharedPreferences.getBoolean("LockOrientation", true)) { 
     int orientation = sharedPreferences.getInt("Orientation", Configuration.ORIENTATION_LANDSCAPE); 
     if(orientation == Configuration.ORIENTATION_LANDSCAPE) { 
      return ActivityInfo.SCREEN_ORIENTATION_SENSOR_LANDSCAPE; 
     } 
     else { 
      return ActivityInfo.SCREEN_ORIENTATION_SENSOR_PORTRAIT; 
     } 
    } 
    return ActivityInfo.SCREEN_ORIENTATION_USER; 
} 
+1

Spiacente, questo non funziona. I valori ScreenOrientation sono valori finali e non risorse. Quindi l'IDE genererà un errore su ogni riga! = 'Return ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE' che è 0 – Altoyyr