2016-12-06 32 views
0

我想創建一個AlertDialog這樣的:無法創建AlertDialog:程序兼容性錯誤

counterButton.setOnLongClickListener(new View.OnLongClickListener() { 
    @Override 
    public boolean onLongClick(View v) { 

     new AlertDialog.Builder(context) 
       .setTitle("Delete entry") 
       .setMessage("Are you sure you want to delete this entry?") 
       .setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() { 
        public void onClick(DialogInterface dialog, int which) { 
         // continue with delete 
        } 
       }) 
       .setNegativeButton(android.R.string.no, new DialogInterface.OnClickListener() { 
        public void onClick(DialogInterface dialog, int which) { 
         // do nothing 
        } 
       }) 
       .setIcon(android.R.drawable.ic_dialog_alert) 
       .show(); // <------- crashes here 

     return true; 
    } 
}); 

我使用的是程序兼容性主題爲我的應用程序。這裏是我的AndroidManifest.xmlapplication元素:

<application 
    android:allowBackup="true" 
    android:icon="@mipmap/ic_launcher" 
    android:label="@string/app_name" 
    android:theme="@style/Theme.AppCompat.Light.NoActionBar"> 
    <activity 
     android:name=".MainActivity" 
     android:label="@string/app_name" 
     android:screenOrientation="portrait" 
     > 
     <intent-filter> 
      <action android:name="android.intent.action.MAIN" /> 
      <category android:name="android.intent.category.LAUNCHER" /> 
     </intent-filter> 
    </activity> 
</application> 

正如你看到的,我的主題設置爲@style/Theme.AppCompat.Light.NoActionBar。 但每當我運行我的應用程序崩潰並出現以下錯誤信息:

java.lang.IllegalStateException: You need to use a Theme.AppCompat theme (or descendant) with this activity. 

我GOOGLE了一番,發現在這麼幾個類似的問題,但沒能解決問題。我正在使用AppCompat主題,那麼我做錯了什麼?

+0

是否有可能在MainActivity中設置了xml佈局中的另一個主題? – Jaythaking

+0

@Jaythaking,謝謝!我剛剛檢查過。我沒有在我的'activity_main.xml'中指定任何主題。 –

+0

您傳遞給'AlertDialog.Builder'的是什麼'context'?它是你的Activity還是'getApplicationContext()'? – ianhanniballake

回答

3

因爲你的主題是關係到你的Activity,你必須將它作爲contextAlertDialog.Builder - getApplicationContext()沒有主題附加到它,這就是爲什麼你得到一個錯誤。

+0

謝謝!那就是問題所在。 –

1

的錯誤說

You need to use a Theme.AppCompat theme 

,那麼你將創建樣式延長AppTheme

!-- Base application theme. --> 
<style name="AppTheme" parent="AppTheme.Base"/> 

<style name="AppTheme.Base" parent="Theme.AppCompat.Light.DarkActionBar"> 
    <!-- Customize your theme here. --> 



<activity 
     android:name=".MainActivity" 
     android:label="@string/app_name" 
     android:screenOrientation="portrait" 
     android:theme="@style/AppTheme" 
     > 
     <intent-filter> 
      <action android:name="android.intent.action.MAIN" /> 
      <category android:name="android.intent.category.LAUNCHER" /> 
     </intent-filter> 
    </activity> 
+0

與直接使用'android:theme =「@ style/Theme.AppCompat.Light.NoActionBar」>'不一樣嗎? –

+0

是的,但它在每個活動 –

+0

感謝您的建議。我剛剛嘗試過,並且仍然出現同樣的錯誤:( –