У меня есть BasicActivity, и я хочу показать AlertDialog, когда пользователь нажимает кнопку Floating Action. Когда я смотрю на FAB: приложение останавливается с этой ошибкой:
java.lang.IllegalStateException: You need to use a Theme.AppCompat theme (or descendant) with this activity.
Я попытался изменить тему своей деятельности с (по умолчанию BasicActivity):
android:theme = "@style/AppTheme.NoActionBar"
к
android:theme = "@style/Theme.AppCompat"
но вся деятельность останавливается, когда я открываю ее с этой ошибкой:
This Activity already has an action bar supplied by the window decor. Do not request Window.FEATURE_SUPPORT_ACTION_BAR and set windowActionBar to false in your theme to use a Toolbar instead.
Я видел много вопросов об этой ошибке, но я до сих пор не понимаю. Я использовал только действие по умолчанию (BasicActivity) и хочу показать простой AlertDialog.
Манифест:
<application
android:allowBackup = "true"
android:icon = "@mipmap/ic_launcher"
android:label = "@string/app_name"
android:roundIcon = "@mipmap/ic_launcher_round"
android:supportsRtl = "true"
android:theme = "@style/AppTheme">
<activity
android:name = ".MainActivity"
android:label = "@string/title_activity_main"
android:theme = "@style/AppTheme.NoActionBar">
<intent-filter>
<action android:name = "android.intent.action.MAIN" />
<category android:name = "android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name = ".ListActivity"
android:label = "@string/title_activity_list"
android:launchMode = "singleTop"
android:theme = "@style/AppTheme.NoActionBar"
/>
<activity
android:name = ".AddActivity"
android:label = "@string/title_activity_add"
android:theme = "@style/AppTheme.NoActionBar">
</activity>
<activity
android:name = ".DetailsActivity"
android:label = "@string/title_activity_details"
android:parentActivityName = ".ListActivity"
android:theme = "@style/AppTheme.NoActionBar">
<!-- Parent activity meta-data to support 4.0 and lower -->
<meta-data
android:name = "android.support.PARENT_ACTIVITY"
android:value = ".MainActivity" />
</activity>
</application>
Мероприятия:
public class ListActivity extends AppCompatActivity {
...
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_list);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
...
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
AlertDialog.Builder builder = new AlertDialog.Builder(getApplicationContext());
builder.setIcon(android.R.drawable.ic_dialog_alert);
builder.setTitle("MyTitle");
builder.setMessage("MyMessage);
builder.setCancelable(false);
builder.setPositiveButton("SAVE", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
if (dialog != null) {
dialog.dismiss();
}
}
});
builder.setNegativeButton("NO", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
if (dialog != null) {
dialog.dismiss();
}
}
});
AlertDialog alertDialog = builder.create();
alertDialog.show();
}
});
...
}
}
Обновлено: ошибка не была связана с AppTheme или другими вещами, а только со строкой:
AlertDialog.Builder builder = new AlertDialog.Builder(getApplicationContext());
необходимо заменить на:
AlertDialog.Builder builder = new AlertDialog.Builder(ListActivity.this);
Мне очень жаль, что я просто потратил ваше время, ребята!
Не могу поверить! Ошибка заключалась в строке AlertDialog.Builder builder = new AlertDialog.Builder(getApplicationContext());




в манифесте
// активность, которую вы хотите показать toolbar
<activity android:name = ".YourActivity"
android:theme = "@style/AppTheme.NoActionBar"><!-- ADD THIS LINE -->
в стилях.xml
<style name = "AppTheme.NoActionBar">
<item name = "windowActionBar">false</item>
<item name = "windowNoTitle">true</item>
</style>
добавьте это в свой тег приложения в файле манифеста
<application
android:theme = "@style/Theme.AppCompat.Light"
</application>
Спасибо за ответ. Ошибка была внутри конструктора для AlertDialog.builder
У меня возникла проблема с использованием ключевого слова [this] вместо getApplicationContext(). когда вы используете getApplicationContext(). Он будет применять тему приложения вместо активности.
AlertDialog.Builder builder = new
AlertDialog.Builder(this);
builder.setIcon(android.R.drawable.ic_dialog_alert);
builder.setTitle("MyTitle");
builder.setMessage("MyMessage);
builder.setCancelable(false);
builder.setPositiveButton("SAVE", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
if (dialog != null) {
dialog.dismiss();
}
}
});
Спасибо за ответ. Ошибка была внутри конструктора для AlertDialog.builder
обновите ответ, используйте это вместо getApplicationContext в конструкторе диалога.
Также отметьте Эта тема просто для ясности.