Actionbar homeAsUpIndicator background - colors

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>

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>

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?

Add toolbar in android app [duplicate]

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>

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">

Android - Change the style of a TextView programatically when the styles are custom and controlled by a theme

I am using themes in my android app to control which styles are applied to each element based on the currently selected theme in the manifest.
Within any one theme (of which there may be many) there are a number of styles which I would like to switch between at runtime. For example, i have a style which defines how text should normally look, and another style to define how that same piece of text should look when a code is entered incorrectly.
I cannot reference the #style directly since this is determined by the theme.
I have produced a sample app to illustrate my problem (note that the snippets below ommit some bits and pieces that aren't relevant)
Attrs.xml: (My custom resource references so my layouts don't reference styles directly)
<resources>
<attr name="theme_style_one" format="reference" />
<attr name="theme_style_two" format="reference" />
</resources>
Themes.xml: (Selects the appropriate style to apply based on the theme)
<resources xmlns:android="http://schemas.android.com/apk/res/android">
<style name="ThemeOne" parent="android:Theme">
<item name="theme_style_one">#style/blue</item>
<item name="theme_style_two">#style/red</item>
</style>
<style name="ThemeTwo" parent="android:Theme">
<item name="theme_style_one">#style/green</item>
<item name="theme_style_two">#style/red</item>
</style>
</resources>
Styles.xml (The styles themselves)
<resources xmlns:android="http://schemas.android.com/apk/res/android">
<style name="blue">
<item name="android:textColor">#color/color_blue</item>
</style>
<style name="red">
<item name="android:textColor">#color/color_red</item>
</style>
<style name="green">
<item name="android:textColor">#color/color_green</item>
</style>
</resources>
Colors.xml (Just some colours)
<resources>
<color name="color_blue">#0000FF</color>
<color name="color_green">#00FF00</color>
<color name="color_red">#FF0000</color>
</resources>
activity_main layout:
<TextView
android:id="#+id/txt_text"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:text="#string/hello_world"
style="?theme_style_one" />
activity_main's onCreate:
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
TextView textView = (TextView)findViewById(R.id.txt_text);
textView.setTextAppearance(this, R.attr.theme_style_two);
}
What I would like to achieve is to change the TextView's style to "theme_style_two" programatically. The "SetTextAppearance" command has no effect. I cannot reference the #style/blue directly in this command, because if I changed the theme in the manifest an incorrect style would be applied.
Any help would be much appreciated!
/**
* Gets a colour attribute for the specified theme attribute
*
* #param The activity context so we can get the theme
* #param themeAttr The theme attribute we want to get the style attribute for (e.g. R.attr.text_small)
* #param styleAttr The attribute of the style that we want to get the value for (e.g. android.R.attr.textColor)
* #return The resource ID of the colour (default is black if the style attribute can't be found)
*/
public static int GetColourFromThemeAttribute(Context c, int themeAttr, int styleAttr)
{
// Get the resource ID of the style that the attribute references for the current theme
TypedValue typedValue = new TypedValue();
c.getTheme().resolveAttribute(themeAttr, typedValue, true);
// Define an array of attributes we want to get from the style
int[] attributes = new int[] { styleAttr };
// Get the style attributes from the style that the theme attribute references
TypedArray a = c.obtainStyledAttributes(typedValue.data, attributes);
// Get the colour from the list of style attributes
int colour = a.getColor(0, Color.BLACK);
// Release the typed array
a.recycle();
return colour;
}

Resources