Add toolbar in android app [duplicate] - android-layout

This question already has answers here:
This Activity already has an action bar supplied by the window decor
(25 answers)
Closed 6 years ago.
I want to add toolbar in my android app but I am getting this error in my StudentDashboardActivity.java at run time after pushing my app on git. I could not find what's the problem behind of it.
FATAL EXCEPTION: main
Process: com.technerdshub.vusocial, PID: 31319
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.technerdshub.vusocial/com.technerdshub.vusocial.Activities.StudentDashboardActivity}: java.lang.IllegalStateException: 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.
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2693)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2758)
at android.app.ActivityThread.access$900(ActivityThread.java:177)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1448)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:145)
at android.app.ActivityThread.main(ActivityThread.java:5942)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at
com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1389)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1184)
Caused by: java.lang.IllegalStateException: 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.
at android.support.v7.app.AppCompatDelegateImplV7.setSupportActionBar(AppCompatDelegateImplV7.java:198)
at android.support.v7.app.AppCompatActivity.setSupportActionBar(AppCompatActivity.java:130)
at com.technerdshub.vusocial.Activities.StudentDashboardActivity.onCreate(StudentDashboardActivity.java:51)
at android.app.Activity.performCreate(Activity.java:6289)
StudentDashboardActivity.java
package com.technerdshub.vusocial.Activities;
import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.design.widget.TabLayout;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v7.app.ActionBarActivity;
import android.support.v7.widget.Toolbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import com.google.android.gms.appindexing.Action;
import com.google.android.gms.appindexing.AppIndex;
import com.google.android.gms.common.api.GoogleApiClient;
import com.technerdshub.vusocial.Fragments.TaskFragment;
import com.technerdshub.vusocial.Fragments.dummy.DummyContent;
import com.technerdshub.vusocial.R;
import java.util.ArrayList;
import java.util.List;
public class StudentDashboardActivity extends AppCompatActivity {
private Toolbar toolbar;
private TabLayout tabLayout;
private ViewPager viewPager;
/**
* ATTENTION: This was auto-generated to implement the App Indexing API.
* See https://g.co/AppIndexing/AndroidStudio for more information.
*/
private GoogleApiClient client;
#Override
protected void onCreate(Bundle savedInstanceState) {
displayLoginActivity();
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_student_dashboard);
// Parse.initialize(new Parse.Configuration.Builder(this)
// .applicationId("J5CIV2z6xeSCXDqdOfhE0kPSikvRFPyDyOJxqJNx")
// .clientKey("bEWm4nWtWiBrMczGfOvA7s4Ulr2bAU3W3TtVSLDf")
// .build()
// );
toolbar = (Toolbar) findViewById(R.id.tool_bar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setElevation(2);
viewPager = (ViewPager) findViewById(R.id.viewpager);
setupViewPager(viewPager);
tabLayout = (TabLayout) findViewById(R.id.tabs);
tabLayout.setupWithViewPager(viewPager);
// ParseObject testObject = new ParseObject("Task");
// testObject.put("marks", 99);
// testObject.saveInBackground();
// ATTENTION: This was auto-generated to implement the App Indexing API.
// See https://g.co/AppIndexing/AndroidStudio for more information.
client = new GoogleApiClient.Builder(this).addApi(AppIndex.API).build();
}
private void setupViewPager(ViewPager viewPager) {
ViewPagerAdapter adapter = new ViewPagerAdapter(getSupportFragmentManager());
adapter.addFragment(new TaskFragment(), "Quiz");
adapter.addFragment(new TaskFragment(), "Assignment");
adapter.addFragment(new TaskFragment(), "GDB");
viewPager.setAdapter(adapter);
}
private void displayLoginActivity() {
Intent i = new Intent(this, Login.class);
startActivity(i);
}
#Override
public void onStart() {
super.onStart();
// ATTENTION: This was auto-generated to implement the App Indexing API.
// See https://g.co/AppIndexing/AndroidStudio for more information.
client.connect();
Action viewAction = Action.newAction(
Action.TYPE_VIEW, // TODO: choose an action type.
"StudentDashboard Page", // TODO: Define a title for the content shown.
// TODO: If you have web page content that matches this app activity's content,
// make sure this auto-generated web page URL is correct.
// Otherwise, set the URL to null.
Uri.parse("http://host/path"),
// TODO: Make sure this auto-generated app URL is correct.
Uri.parse("android-app://com.technerdshub.vusocial.Activities/http/host/path")
);
AppIndex.AppIndexApi.start(client, viewAction);
}
#Override
public void onStop() {
super.onStop();
// ATTENTION: This was auto-generated to implement the App Indexing API.
// See https://g.co/AppIndexing/AndroidStudio for more information.
Action viewAction = Action.newAction(
Action.TYPE_VIEW, // TODO: choose an action type.
"StudentDashboard Page", // TODO: Define a title for the content shown.
// TODO: If you have web page content that matches this app activity's content,
// make sure this auto-generated web page URL is correct.
// Otherwise, set the URL to null.
Uri.parse("http://host/path"),
// TODO: Make sure this auto-generated app URL is correct.
Uri.parse("android-app://com.technerdshub.vusocial.Activities/http/host/path")
);
AppIndex.AppIndexApi.end(client, viewAction);
client.disconnect();
}
class ViewPagerAdapter extends FragmentPagerAdapter {
private final List<TaskFragment> mFragmentList = new ArrayList<>();
private final List<String> mFragmentTitleList = new ArrayList<>();
public ViewPagerAdapter(FragmentManager manager) {
super(manager);
}
#Override
public TaskFragment getItem(int position) {
return mFragmentList.get(position);
}
#Override
public int getCount() {
return mFragmentList.size();
}
public void addFragment(TaskFragment fragment, String title) {
mFragmentList.add(fragment);
mFragmentTitleList.add(title);
}
#Override
public CharSequence getPageTitle(int position) {
return mFragmentTitleList.get(position);
}
}
}
style.xml
<resources xmlns:tools="http://schemas.android.com/tools">
<!-- Base application theme. -->
<style name="AppTheme" parent="Theme.AppCompat.Light">
<!-- Customize your theme here. -->
<item name="colorPrimary">#color/ColorPrimary</item>
<item name="colorPrimaryDark">#color/ColorPrimaryDark</item>
<item name="colorAccent">#color/colorAccent</item>
<item name="windowActionBar">false</item>
<item name="windowNoTitle">true</item>
</style>
<!--<style name="AppTheme.NoActionBar" parent="Theme.AppCompat.NoActionBar">-->
<!--<item name="windowActionBar">false</item>-->
<!--<item name="windowNoTitle">true</item>-->
<!--</style>-->
<style name="AppTheme.AppBarOverlay" parent="ThemeOverlay.AppCompat.Dark.ActionBar" >
</style>
<style name="AppTheme.PopupOverlay" parent="ThemeOverlay.AppCompat.Light" />
<style name="TEST" parent="AppTheme" >
<item name="colorPrimary">#color/com_facebook_blue</item>
<item name="colorAccent">#color/colorAccent</item>
<item name="android:colorBackground">#color/cardview_light_background</item>
<item name="colorPrimaryDark">#color/com_facebook_button_background_color_selected</item>
</style>
<!--<!– new design fai–>-->
<!--<style name="MyMaterialTheme" parent="MyMaterialTheme.Base">-->
<!--</style>-->
<!--<style name="MyMaterialTheme.Base" parent="Theme.AppCompat.Light.NoActionBar">-->
<!--<item name="windowNoTitle">true</item>-->
<!--<item name="windowActionBar">false</item>-->
<!--<item name="colorPrimary">#color/colorPrimary</item>-->
<!--<item name="colorPrimaryDark">#color/colorPrimaryDark</item>-->
<!--<item name="colorAccent">#color/colorAccent</item>-->
<!--</style>-->
</resources>
Please tell me, how can I resolve this error?

Try to change style.xml to below given code
<style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar">
<!-- Customize your theme here. -->
<item name="android:windowActionBar">false</item>
<item name="colorPrimary">#color/colorPrimary</item>
<item name="colorPrimaryDark">#color/colorPrimaryDark</item>
<item name="colorAccent">#color/colorAccent</item>
</style>
<style name="AppTheme.NoActionBar">
<item name="windowActionBar">false</item>
<item name="windowNoTitle">true</item>
</style>

Declare the app Theme with windowActionBar as false in style.xml
<item name="windowActionBar">false</item>
if you have used any app support library for the theme need to include below line also
<item name="windowNoTitle">true</item>

Related

Change background color of fragments dynamically from a switch

I am trying to have all fragments change to the background color of red using a SwitchPreferenceCompat but am having trouble writing the listener code and MainActivity code. I have tried some things but am not too familiar with how to write the listener code to be able to write the mainactivity code to use it properly. I am not really looking for a solution but rather being pointed in the right direction.
Thank you
Here's the relevant code:
Preferences xml
<?xml version="1.0" encoding="utf-8"?>
<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">
<PreferenceCategory android:title="Game Settings">
<SeekBarPreference
android:defaultValue="10"
android:key="pennyCount"
android:max="20"
android:summary="#string/starting_penny_count_new_game"
android:title="#string/starting_penny_count"
app:min="1"
app:showSeekBarValue="true" />
<SwitchPreferenceCompat
android:key="fastAI"
android:summary="#string/fast_ai_summary"
android:title="#string/fast_ai" />
</PreferenceCategory>
<PreferenceCategory android:title="Theme Settings">
<DropDownPreference
android:defaultValue="AppTheme"
android:entries="#array/themes"
android:entryValues="#array/theme_values"
android:key="theme"
android:title="#string/app_theme"
app:useSimpleSummaryProvider="true" />
<ListPreference
android:defaultValue="System"
android:entries="#array/theme_modes"
android:entryValues="#array/theme_mode_values"
android:key="themeMode"
android:title="#string/theme_mode"
app:useSimpleSummaryProvider="true" />
</PreferenceCategory>
<PreferenceCategory android:title="About the App">
<Preference
android:key="credits"
android:summary="#string/about_app_summary"
android:title="#string/about_penny_drop" />
</PreferenceCategory>
<SwitchPreferenceCompat
android:defaultValue="false"
android:key="switchRed"
android:title="Turn Background Color Red"
app:theme="#style/SwitchTheme"/>
</PreferenceScreen>
MainActivity.kt
package dev.mfazio.pennydrop
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.text.style.BackgroundColorSpan
import android.view.Menu
import android.view.MenuItem
import android.widget.Switch
import androidx.appcompat.app.AppCompatDelegate
import androidx.navigation.NavController
import androidx.navigation.fragment.NavHostFragment
import androidx.navigation.ui.AppBarConfiguration
import androidx.navigation.ui.onNavDestinationSelected
import androidx.navigation.ui.setupActionBarWithNavController
import androidx.navigation.ui.setupWithNavController
import androidx.preference.PreferenceManager
import com.google.android.material.bottomnavigation.BottomNavigationView
class MainActivity : AppCompatActivity() {
private lateinit var navController: NavController
override fun onCreate(savedInstanceState: Bundle?) {
val prefs =
PreferenceManager.getDefaultSharedPreferences(this)
val themeId = when (prefs.getString("theme", "AppTheme")) {
"Crew" -> R.style.Crew
"FTD" -> R.style.FTD
"GPG" -> R.style.GPG
"Hazel" -> R.style.Hazel
"Kotlin" -> R.style.Kotlin
else -> R.style.AppTheme
}
setTheme(themeId)
val nightMode = when (prefs.getString("themeMode", "")) {
"Light" -> AppCompatDelegate.MODE_NIGHT_NO
"Dark" -> AppCompatDelegate.MODE_NIGHT_YES
else -> AppCompatDelegate.MODE_NIGHT_FOLLOW_SYSTEM
}
AppCompatDelegate.setDefaultNightMode(nightMode)
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
val navHostFragment =
supportFragmentManager.findFragmentById(R.id.containerFragment) as NavHostFragment
this.navController = navHostFragment.navController
val bottomNav = findViewById<BottomNavigationView>(R.id.bottom_nav)
bottomNav.setupWithNavController(this.navController)
val appBarConfiguration = AppBarConfiguration(bottomNav.menu)
setupActionBarWithNavController(this.navController, appBarConfiguration)
}
override fun onCreateOptionsMenu(menu: Menu?): Boolean {
super.onCreateOptionsMenu(menu)
menuInflater.inflate(R.menu.options, menu)
return true
}
override fun onOptionsItemSelected(item: MenuItem): Boolean =
if (this::navController.isInitialized) {
item.onNavDestinationSelected(this.navController) ||
super.onOptionsItemSelected(item)
} else false
override fun onSupportNavigateUp(): Boolean =
(this::navController.isInitialized && this.navController.navigateUp()) ||
super.onSupportNavigateUp()
}
SettingFragment
package dev.mfazio.pennydrop.fragments
import android.os.Bundle
import android.util.Log
import androidx.appcompat.app.AppCompatDelegate
import androidx.navigation.fragment.findNavController
import androidx.preference.*
import dev.mfazio.pennydrop.R
class SettingsFragment : PreferenceFragmentCompat() {
override fun onCreatePreferences(
savedInstanceState: Bundle?,
rootKey: String?
) {
setPreferencesFromResource(R.xml.preferences, rootKey)
val themePreference = findPreference<DropDownPreference?>("theme")
val themeModePreference = findPreference<ListPreference?>("themeMode")
val creditsPreference = findPreference<Preference?>("credits")
val switchPreference = findPreference<SwitchPreferenceCompat>("switchRed")
themePreference?.onPreferenceChangeListener =
Preference.OnPreferenceChangeListener { _, _ ->
activity?.recreate()
true
}
themeModePreference?.setDefaultValue(AppCompatDelegate.MODE_NIGHT_FOLLOW_SYSTEM)
themeModePreference?.onPreferenceChangeListener =
Preference.OnPreferenceChangeListener { _, newValue ->
val nightMode = when (newValue?.toString()) {
"Light" -> AppCompatDelegate.MODE_NIGHT_NO
"Dark" -> AppCompatDelegate.MODE_NIGHT_YES
else -> AppCompatDelegate.MODE_NIGHT_FOLLOW_SYSTEM
}
AppCompatDelegate.setDefaultNightMode(nightMode)
true
}
creditsPreference?.onPreferenceClickListener =
Preference.OnPreferenceClickListener { _ ->
this.findNavController().navigate(R.id.aboutFragment)
true
}
}
}
Styles xml
<resources>
<style name="AppTheme" parent="Theme.MaterialComponents.DayNight">
<item name="colorPrimary">#color/colorPrimary</item>
<item name="colorPrimaryDark">#color/colorPrimaryDark</item>
<item name="colorAccent">#color/colorAccent</item>
<item name="colorSurface">#color/nightLightGray</item>
</style>
<style name="Kotlin" parent="AppTheme">
<item name="colorPrimary">#color/kotlinBlue</item>
<item name="colorPrimaryDark">#color/kotlinPurple</item>
<item name="colorAccent">#color/kotlinOrange</item>
</style>
<style name="Crew" parent="AppTheme">
<item name="colorPrimary">#color/crewBlue</item>
<item name="colorPrimaryDark">#color/crewLightBlue</item>
<item name="colorAccent">#color/crewGold</item>
<item name="colorSurface">#color/crewBlue</item>
</style>
<style name="FTD" parent="AppTheme">
<item name="colorPrimary">#color/ftdGreen</item>
<item name="colorPrimaryDark">#color/ftdGreen</item>
<item name="colorAccent">#color/ftdBlue</item>
</style>
<style name="GPG" parent="AppTheme">
<item name="colorPrimary">#color/packGreen</item>
<item name="colorPrimaryDark">#color/packGreen</item>
<item name="colorAccent">#color/packGold</item>
<item name="colorSurface">#color/packGreenDark</item>
</style>
<style name="Hazel" parent="AppTheme">
<item name="colorPrimary">#color/hazelBlue</item>
<item name="colorPrimaryDark">#color/hazelDarkBlue</item>
<item name="colorAccent">#color/hazelPink</item>
</style>
<style name="SwitchTheme" parent="AppTheme">
<item name="android:colorBackground">#FF0000</item>
</style>
</resources>

Component not showing in design view for navigation drawer android studio [duplicate]

I created the app and I want to use navigation drawer menu, but when I tried to edit in navigation drawer xml, then the problem "Waiting for build to finish..." happened and I don't see layout previw on left side of android studio
to relate
layout_preview not found here
I tried this soultion to solve this issue but unfortunately not working for me
this is activity_main_drawer.xml
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
tools:showIn="navigation_view">
<group android:checkableBehavior="single">
<item
android:id="#+id/articles"
android:icon="#drawable/ic_menu_camera"
android:title="#string/articles" />
<item
android:id="#+id/windows"
android:icon="#drawable/ic_menu_gallery"
android:title="#string/windows" />
<item
android:id="#+id/linux"
android:icon="#drawable/ic_menu_slideshow"
android:title="#string/linux" />
<item
android:id="#+id/miscellaneous_devices"
android:icon="#drawable/ic_menu_manage"
android:title="#string/miscellaneous_devices" />
<item
android:id="#+id/information_security"
android:icon="#drawable/ic_menu_manage"
android:title="#string/information_security" />
<item
android:id="#+id/facebook"
android:icon="#drawable/ic_menu_manage"
android:title="#string/facebook" />
</group>
<item android:title="Communicate">
<menu>
<item
android:id="#+id/nav_share"
android:icon="#drawable/ic_menu_share"
android:title="Share" />
<item
android:id="#+id/nav_send"
android:icon="#drawable/ic_menu_send"
android:title="Send" />
</menu>
</item>
</menu>
activity_main
package www.pro.cs_is.com.procsis;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.view.View;
import android.support.design.widget.NavigationView;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
public class MainActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.addDrawerListener(toggle);
toggle.syncState();
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
}
#Override
public void onBackPressed() {
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
super.onBackPressed();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
#SuppressWarnings("StatementWithEmptyBody")
#Override
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
int id = item.getItemId();
if (id == R.id.miscellaneous_devices) {
// Handle the camera action
} else if (id == R.id.articles) {
} else if (id == R.id.windows) {
} else if (id == R.id.linux) {
} else if (id == R.id.facebook) {
} else if (id == R.id.information_security) {
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
}
Update 1 : After many attempts it's seems a general Issue after update IDE to version 3.1.2, till now there's only one solution which #mtak suggested although it is similar to the top menu options in the preview
Remove the line
tools:showIn="navigation_view"
from activity_main_drawer.xml and rebuild.
This solved the same problem for me.
Don't know why!!!
Problem solved in AS 3.1.3(8 June 2018) and reappeared again (16 June 2018)!!!
New temporary workaround:
Cut the line tools:showIn="navigation_view" from the menu file.
Close the menu file.
Reopen it and paste the line.
Go to design and see the menu as it should be.
If you close the menu file and reopen it the problem comes back!
Still no preview in Text.
You can try the following:
Run Build then try to see the preview again
Close the current layout,open another then reopen again
Because you extend AppCompatActivity, you need to make sure that in your styles.xml your AppTheme is a descendant of AppCompat
<style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
<!-- Customize your theme here. -->
<item name="colorPrimary">#color/colorPrimary</item>
<item name="colorPrimaryDark">#color/colorPrimaryDark</item>
<item name="colorAccent">#color/colorAccent</item>
</style>
That worked for me while the accepted answer for not that helping.
I have found the solution. Remove these two tool lines and close/reopen:
xmlns:tools = "http://schemas.android.com/tools"
tools:showIn = "navigation_view"
Actually this problem is because you have extended your activity with AppComactActivity and your theme parent is not the Theme.AppCompat use this theme as your default in manifest.xml under application tag. your style should look like as
<style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
</style>
rebuilduing the project worked for me

This Activity already has an action bar supplied by the window decor. not solvable with AppTheme

Yeah as you can see above I get the mentioned Error. But I'm 100% sure the Activity's theme doesn't have an Action Bar. I'm trying to get de Toolbar working but every time I open the Activity the App crashes.
Here is the full Stacktrace
2019-12-10 22:32:54.796 27068-27068/com.simplemobiletools.studentcalendarpaid.debug E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.simplemobiletools.studentcalendarpaid.debug, PID: 27068
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.simplemobiletools.studentcalendarpaid.debug/com.simplemobiletools.studentcalendarpaid.activities.MainActivity}: java.lang.IllegalStateException: 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.
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3047)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3182)
at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:78)
at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:108)
at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:68)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1916)
at android.os.Handler.dispatchMessage(Handler.java:106)
at android.os.Looper.loop(Looper.java:193)
at android.app.ActivityThread.main(ActivityThread.java:6898)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:537)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:858)
Caused by: java.lang.IllegalStateException: 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.
at androidx.appcompat.app.AppCompatDelegateImpl.setSupportActionBar(AppCompatDelegateImpl.java:345)
at androidx.appcompat.app.AppCompatActivity.setSupportActionBar(AppCompatActivity.java:130)
at com.simplemobiletools.studentcalendarpaid.activities.MainActivity.toolBar(MainActivity.kt:192)
at com.simplemobiletools.studentcalendarpaid.activities.MainActivity.onCreate(MainActivity.kt:178)
at android.app.Activity.performCreate(Activity.java:7149)
at android.app.Activity.performCreate(Activity.java:7140)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1288)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3027)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3182) 
at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:78) 
at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:108) 
at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:68) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1916) 
at android.os.Handler.dispatchMessage(Handler.java:106) 
at android.os.Looper.loop(Looper.java:193) 
at android.app.ActivityThread.main(ActivityThread.java:6898) 
at java.lang.reflect.Method.invoke(Native Method) 
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:537) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:858) 
2019-12-10 22:32:54.800 27068-27068/com.simplemobiletools.studentcalendarpaid.debug W/OPDiagnose: getService:OPDiagnoseService NULL
2019-12-10 22:32:54.817 27068-27068/com.simplemobiletools.studentcalendarpaid.debug I/Process: Sending signal. PID: 27068 SIG: 9
Here you can see the main Activity
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(com.simplemobiletools.studentcalendarpaid.R.layout.activity_main)
appLaunched(com.simplemobiletools.studentcalendarpaid.BuildConfig.APPLICATION_ID)
prefs = getSharedPreferences("com.simplemobiletools.studentcalendarpro", MODE_PRIVATE);
prefs = getSharedPreferences("com.simplemobiletools.studentcalendarpro", MODE_PRIVATE);
/*
prefs = getSharedPreferences("com.simplemobiletools.studentcalendarpro", MODE_PRIVATE)
if (prefs!!.getBoolean("firstrun", true)) {
val h = Intent(this#GradeMainActivity, OnBoardingActivity::class.java)
startActivity(h)
prefs!!.edit().putBoolean("firstrun", false).apply();
}
*/
drawerLayout = findViewById(com.simplemobiletools.studentcalendarpaid.R.id.drawer_layout)
navigationView = findViewById(com.simplemobiletools.studentcalendarpaid.R.id.nav_view)
navigationView!!.bringToFront()
navigationView!!.setNavigationItemSelectedListener(this)
/*
val toggle = ActionBarDrawerToggle(this, drawerLayout, toolbar,
R.string.navigation_draw_open, R.string.navigation_draw_close)
drawerLayout!!.addDrawerListener(toggle)
toggle.syncState()
*/
/*
checkWhatsNewDialog()
calendar_fab.beVisible()
*/
calendar_fab.setOnClickListener {
launchNewEventIntent(currentFragments.last().getNewEventDayCode())
}
storeStateVariables()
if (resources.getBoolean(com.simplemobiletools.studentcalendarpaid.R.bool.portrait_only)) {
requestedOrientation = ActivityInfo.SCREEN_ORIENTATION_PORTRAIT
}
if (!hasPermission(PERMISSION_WRITE_CALENDAR) || !hasPermission(PERMISSION_READ_CALENDAR)) {
config.caldavSync = false
}
if (config.caldavSync) {
refreshCalDAVCalendars(false)
}
swipe_refresh_layout.setOnRefreshListener {
refreshCalDAVCalendars(false)
}
if (!checkViewIntents()) {
return
}
if (!checkOpenIntents()) {
updateViewPager()
}
checkAppOnSDCard()
updateViewPager()
toolBar()
}
private fun toolBar() {
val tb = findViewById<Toolbar>(R.id.myToolbar)
tb.setTitle("Android Toolbar");
// tb.setTitleTextAppearance(this, R.style.toolbarTitle);
// tb.setSubtitle("My SubTitle");
// tb.setSubtitleTextAppearance(this, R.style.toolbarSubTitle);
// tb.setContentInsetsAbsolute(0, 54); // Best used when setting a Logo
// tb.setContentInsetsRelative(0, 54); // Best used when setting a Logo
// tb.setLogo(R.mipmap.ic_launcher);
setSupportActionBar(tb)
if (getSupportActionBar() != null) {
// This sets a shadow underneath the Toolbar
getSupportActionBar()?.setElevation(8F);
}
}
override fun onNavigationItemSelected(item: MenuItem): Boolean {
// Handle navigation view item clicks here.
// here is the main place where we need to work on.
val id = item.itemId
when (id) {
com.simplemobiletools.studentcalendarpaid.R.id.nav_calendar -> {
val h = Intent(this#MainActivity, MainActivity::class.java)
startActivity(h)
}
/*
com.simplemobiletools.studentcalendarpro.R.id.nav_account -> {
val l = Intent(this#GradeMainActivity, AccountActivity::class.java)
startActivity(l)
}*/
com.simplemobiletools.studentcalendarpaid.R.id.nav_todo -> {
/*Falls ich Fragments gebrauchen will
//val fragment = ToDoFragment()
//displayFragment(fragment)
//supportFragmentManager.beginTransaction().add(R.id.fragments_holder, fragment).commitNow()
*/
val m = Intent(this#MainActivity, TodoActivity::class.java)
startActivity(m)
}
R.id.nav_grades -> {
val i = Intent(this#MainActivity, AddGradeActivity::class.java)
startActivity(i)
}
com.simplemobiletools.studentcalendarpaid.R.id.nav_info -> {
val k = Intent(this#MainActivity, com.simplemobiletools.studentcalendarpaid.activities.InfoActivity::class.java)
startActivity(k)
}
com.simplemobiletools.studentcalendarpaid.R.id.nav_overview -> {
val j = Intent(this#MainActivity, ViewListContents::class.java)
startActivity(j)
}
}// this is done, now let us go and intialise the home page.
// after this lets start copying the above.
// FOLLOW MEEEEE>>>
val drawer = findViewById<View>(com.simplemobiletools.studentcalendarpaid.R.id.drawer_layout) as DrawerLayout
drawer.closeDrawer(GravityCompat.START)
return true
updateViewPager()
}
private fun displayFragment(fragment: Fragment) {
supportFragmentManager
.beginTransaction()
.replace(R.id.fragments_holder, fragment)
.commit()
}
and here my styles.xml
<resources>
<style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar">
<item name="windowActionBar">false</item>
<item name="windowNoTitle">true</item>
</style>
<style name="AppTheme2" parent="Theme.AppCompat.Light.NoActionBar">
<item name="windowActionBar">false</item>
<item name="windowNoTitle">true</item>
</style>
<style name="AppTheme.NoActionBar">
<item name="windowActionBar">false</item>
<item name="windowNoTitle">true</item>
</style>
<style name="SplashTheme" parent="Theme.AppCompat.Light.NoActionBar" >
</style>
<style name="AppTheme.AppBarOverlay" parent="ThemeOverlay.AppCompat.Dark.ActionBar" />
<style name="TextAppearance44">
<item name="android:textColor">#ffff</item>
<item name="android:textSize">16sp</item>
</style>
<style name="AppTheme1" parent="Theme.AppCompat.Light.NoActionBar">
<item name="windowActionBar">false</item>
<item name="windowNoTitle">true</item>
</style>
<style name="AudioFileInfoOverlayText">
<item name="android:paddingLeft">4px</item>
<item name="android:paddingBottom">4px</item>
<item name="android:textColor">#ffffffff</item>
<item name="android:textSize">12sp</item>
<item name="android:shadowColor">#000000</item>
<item name="android:shadowDx">1</item>
<item name="android:shadowDy">1</item>
<item name="android:shadowRadius">1</item>
</style>
<style name="AppTheme.PopupOverlay" parent="ThemeOverlay.AppCompat.Light" />
<style name="DayView">
<item name="android:gravity">center</item>
<item name="android:textSize">#dimen/day_text_size</item>
<item name="android:fontFamily">sans-serif-light</item>
</style>
<style name="MetaView" parent="DayView">
<item name="android:textStyle">bold</item>
<item name="android:textSize">#dimen/meta_text_size</item>
</style>
<style name="WeekNumberStyle">
<item name="android:textStyle">bold</item>
<item name="android:gravity">top|center_horizontal</item>
<item name="android:textSize">#dimen/day_monthly_text_size</item>
<item name="android:textColor">#color/default_text_color</item>
<item name="android:fontFamily">sans-serif-light</item>
</style>
<style name="ArrowStyle">
<item name="android:background">?android:attr/selectableItemBackgroundBorderless</item>
</style>
<style name="MonthStyle">
<item name="android:background">?android:attr/selectableItemBackground</item>
</style>
</resources>
and here the important thing in my Main Application
toolBar()
}
private fun toolBar() {
val tb = findViewById<Toolbar>(R.id.myToolbar)
tb.setTitle("Android Toolbar");
// tb.setTitleTextAppearance(this, R.style.toolbarTitle);
// tb.setSubtitle("My SubTitle");
// tb.setSubtitleTextAppearance(this, R.style.toolbarSubTitle);
// tb.setContentInsetsAbsolute(0, 54); // Best used when setting a Logo
// tb.setContentInsetsRelative(0, 54); // Best used when setting a Logo
// tb.setLogo(R.mipmap.ic_launcher);
setSupportActionBar(tb)
if (getSupportActionBar() != null) {
// This sets a shadow underneath the Toolbar
getSupportActionBar()?.setElevation(8F);
}
}
Here is also my Manifest.xml
<activity
android:name="com.simplemobiletools.studentcalendarpaid.activities.MainActivity"
android:theme="#style/AppTheme2"
android:launchMode="singleTask">
<meta-data
android:name="android.app.default_searchable"
android:resource="#xml/searchable"/>
<intent-filter>
<action android:name="android.intent.action.SEARCH"/>
</intent-filter>
<intent-filter>
<action android:name="android.intent.action.VIEW"/>
<category android:name="android.intent.category.DEFAULT"/>
<data android:scheme="content"/>
<data android:scheme="file"/>
<data android:mimeType="text/x-vcalendar"/>
<data android:mimeType="text/calendar"/>
</intent-filter>
<intent-filter>
<action android:name="android.intent.action.VIEW"/>
<category android:name="android.intent.category.DEFAULT"/>
<data android:mimeType="time/epoch"/>
<data android:host="com.android.calendar"/>
<data android:scheme="content"/>
</intent-filter>
<intent-filter
tools:ignore="AppLinkUrlError">
<action android:name="android.intent.action.VIEW"/>
<category android:name="android.intent.category.DEFAULT"/>
<data android:mimeType="vnd.android.cursor.item/event"/>
</intent-filter>
</activity>
As you can see I set the AppTheme to NoActionBar and still get this Error:
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.
Does somebody know the answer?

Actionbar homeAsUpIndicator background

I am using this code in styles.xml but my button background does not change.
Where i am doing wrong?
<style name="MyCustomTheme" parent="#android:style/Theme.Holo.Light">
<item name="android:actionBarStyle">#style/MyActionBar</item>
</style>
<style name="MyActionBar" parent="#android:style/Widget.Holo.Light.ActionBar">
<item name="android:homeAsUpIndicator">#drawable/actionbar_buttonbg</item>
<item name="android:background">#drawable/actionbar_bg</item>
</style>
Unfortunately you can not add a background to homeAsUpIndicator via styles.xml.
However you can do it programatically:
public void setHomeAsUpBackgroundResource(int resource) {
View abView = findViewById(R.id.action_bar);
if (abView != null && abView instanceof ViewGroup) {
ViewGroup vgAb = (ViewGroup) abView;
if (vgAb.getChildCount() > 0) {
View child = vgAb.getChildAt(0);
if (child != null && child instanceof ImageButton)
child.setBackgroundResource(resource);
}
}
}
It is hacky: it relies on two assumptions: this button is the first child of the action bar and is an instance of ImageButton.
Hi try use in style properties actionBarItemBackground good luck
<style name="MyActionBar" parent="#android:style/Widget.Holo.Light.ActionBar">
<item name="android:homeAsUpIndicator">#drawable/actionbar_buttonbg</item>
<item name="android:background">#drawable/actionbar_bg</item>
<item name="actionBarItemBackground">#color/backGroundHomeAsUp</item>
<item name="android:actionBarItemBackground">#color/backGroundHomeAsUp</item>
</style>

Style not applying for AlertDialog with DialogFragment

I'm using a `DialogFragment' to display alert dialog. My requirement is to have a same theme for all the dialog fragment's in the appllicaiton across different versions of Android starting from 2.3. But I'm unable to apply theme. My code is
<style name="Dialog" parent="#android:style/Theme.Dialog">
<item name="android:windowTitleStyle">#style/MyOwnDialogTitle</item>
</style>
<style name="MyOwnDialogTitle" parent="android:Widget.TextView">
<item name="android:background">#android:color/darker_gray</item>
<item name="android:drawableRight">#android:drawable/ic_menu_add</item>
</style>
public class MyDialogFragment extends DialogFragment{
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
Context context = new ContextThemeWrapper(getActivity(), R.style.Dialog);
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("Title");
builder.setMessage("Message");
builder.setPositiveButton("Ok", null);
return builder.create();
}
}
My output on 2.3 emulator is like
Please Help me out.
Thanks,
Sha.
Replace <style name="MyOwnDialogTitle" parent="android:Widget.TextView">
by
<style name="MyOwnDialogTitle" parent="#android:style/Widget.TextView">

Resources