Could not instantiate android.support.design.widget.TextInputLayout - android

I'm trying to use android.support.design.widget.TextInputLayout but i get this exception
java.lang.IllegalArgumentException: You need to use a Theme.AppCompat theme (or descendant) with the design library.
at android.support.design.widget.ThemeUtils.checkAppCompatTheme(ThemeUtils.java:33)
at android.support.design.widget.TextInputLayout.(TextInputLayout.java:193)
at android.support.design.widget.TextInputLayout.(TextInputLayout.java:186)
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
at java.lang.reflect.Constructor.newInstance(Constructor.java:423)
at org.jetbrains.android.uipreview.ViewLoader.createNewInstance(ViewLoader.java:465)
at org.jetbrains.android.uipreview.ViewLoader.loadClass(ViewLoader.java:172)
at org.jetbrains.android.uipreview.ViewLoader.loadView(ViewLoader.java:105)
at com.android.tools.idea.rendering.LayoutlibCallbackImpl.loadView(LayoutlibCallbackImpl.java:186)
at android.view.BridgeInflater.loadCustomView(BridgeInflater.java:334)
at android.view.BridgeInflater.loadCustomView(BridgeInflater.java:345)
at android.view.BridgeInflater.createViewFromTag(BridgeInflater.java:245)
at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:727)
at android.view.LayoutInflater.rInflate_Original(LayoutInflater.java:858)
at android.view.LayoutInflater_Delegate.rInflate(LayoutInflater_Delegate.java:70)
at android.view.LayoutInflater.rInflate(LayoutInflater.java:834)
at android.view.LayoutInflater.rInflateChildren(LayoutInflater.java:821)
at android.view.LayoutInflater.inflate(LayoutInflater.java:518)
at android.view.LayoutInflater.inflate(LayoutInflater.java:397)
at com.android.layoutlib.bridge.impl.RenderSessionImpl.inflate(RenderSessionImpl.java:324)
at com.android.layoutlib.bridge.Bridge.createSession(Bridge.java:429)
at com.android.ide.common.rendering.LayoutLibrary.createSession(LayoutLibrary.java:389)
at com.android.tools.idea.rendering.RenderTask$2.compute(RenderTask.java:548)
at com.android.tools.idea.rendering.RenderTask$2.compute(RenderTask.java:533)
at com.intellij.openapi.application.impl.ApplicationImpl.runReadAction(ApplicationImpl.java:966)
at com.android.tools.idea.rendering.RenderTask.createRenderSession(RenderTask.java:533)
at com.android.tools.idea.rendering.RenderTask.lambda$inflate$70(RenderTask.java:659)
at java.util.concurrent.FutureTask.run(FutureTask.java:266)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
at java.lang.Thread.run(Thread.java:745)
My gradle module file contains:
compile 'com.android.support:design:26.0.1'
compile 'com.android.support:appcompat-v7:26.0.1'
activity-main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
xmlns:app="http://schemas.android.com/apk/res-auto"
tools:context="com.example.eltobgy.yala.MainActivity">
<android.support.design.widget.TextInputLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<AutoCompleteTextView
android:id="#+id/email"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="email"
android:inputType="textEmailAddress"
android:maxLines="1"
android:singleLine="true" />
</android.support.design.widget.TextInputLayout>
</LinearLayout>
styles.xml
<resources>
<style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
</style>
<style name="TextAppearence.App.TextInputLayout" parent="#android:style/TextAppearance">
<item name="android:textColor">#color/colorAccent</item>
</style>
<style name="label_text">
<item name="android:textSize">19sp</item>
<item name="android:textColor">#android:color/black</item>
<item name="android:layout_width">wrap_content</item>
<item name="android:layout_height">wrap_content</item>
</style>
<style name="text">
<item name="android:textSize">14sp</item>
<item name="android:textColor">#color/gray</item>
<item name="android:layout_width">wrap_content</item>
<item name="android:layout_height">wrap_content</item>
</style>
<style name="line">
<item name="android:layout_marginBottom">8dp</item>
<item name="android:layout_marginTop">8dp</item>
<item name="android:layout_width">match_parent</item>
<item name="android:layout_height">1dp</item>
<item name="android:background">#color/colorAccent</item>
<item name="android:shadowColor">#color/colorAccent</item>
<item name="android:shadowDx">0</item>
<item name="android:shadowDy">0</item>
<item name="android:shadowRadius">8</item>
</style>
<!--FIREBASE UI-->
<style name="LoginTheme" parent="FirebaseUI">
<item name="colorPrimary">#color/colorPrimary</item>
<item name="colorPrimaryDark">#color/colorPrimaryDark</item>
<item name="colorAccent">#color/colorAccent</item>
<item name="colorButtonNormal">#color/colorAccent</item>
<item name="colorControlNormal">#android:color/white</item>
<item name="colorControlActivated">#android:color/white</item>
<item name="colorControlHighlight">#android:color/white</item>
<item name="android:textColor">#android:color/white</item>
<item name="android:textColorPrimary">#android:color/white</item>
<item name="android:textColorSecondary">#android:color/white</item>
<item name="android:colorBackground">#color/colorPrimary</item>
<item name="windowActionBar">false</item>
<item name="windowNoTitle">true</item>
<item name="android:textColorHint">#android:color/white</item>
</style>
<style name="FirebaseUI.Text">
<item name="android:layout_width">match_parent</item>
<item name="android:layout_height">wrap_content</item>
<item name="android:fontFamily">sans-serif</item>
<item name="android:textColor">#android:color/white</item>
</style>
<style name="FirebaseUI.Text.Link">
<item name="android:textColor">#color/colorSecondary</item>
</style>
<color name="colorSecondary">#FFC300</color>
<color name="gray">#FFF0</color>
</resources>
MainActivity.java
package com.example.eltobgy.yala;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.widget.TextView;
import android.widget.Toast;
import com.firebase.ui.auth.AuthUI;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.auth.FirebaseUserMetadata;
import com.google.firebase.database.ChildEventListener;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import java.util.Arrays;
import java.util.List;
public class MainActivity extends AppCompatActivity {
private static final String ANONYMOUS = "Anonymous";
// Choose an arbitrary request code value
private static final int RC_SIGN_IN = 1;
Boolean flag_registered = false;
// Firebase
private FirebaseAuth mFirebaseAuth;
private FirebaseAuth.AuthStateListener mAuthStateListener;
private ChildEventListener mChildEventListener;
private String mUsername;
private DatabaseReference mDatabaseReference;
private FirebaseDatabase mDatabase;
private User currentUser;
#Override
protected void onCreate(Bundle savedInstanceState) {
mUsername = ANONYMOUS;
mFirebaseAuth = FirebaseAuth.getInstance();
mDatabase = FirebaseDatabase.getInstance();
currentUser = null;
mDatabaseReference = mDatabase.getReference().child("users");
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mAuthStateListener = new FirebaseAuth.AuthStateListener() {
#Override
public void onAuthStateChanged(#NonNull FirebaseAuth firebaseAuth) {
FirebaseUser firebaseUser = firebaseAuth.getCurrentUser();
if (firebaseUser != null) {
// User is signed in
FirebaseUserMetadata metadata = firebaseAuth.getCurrentUser().getMetadata();
onSignedInInitialize(firebaseUser.getDisplayName());
Toast.makeText(MainActivity.this, "You're now signed in. Welcome " + firebaseUser.getDisplayName() + "!", Toast.LENGTH_SHORT).show();
DatabaseReference userDatabaseRefrence = mDatabaseReference.child(firebaseUser.getUid());
ValueEventListener valueEventListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
currentUser = dataSnapshot.getValue(User.class);
if(currentUser.getCurrentType().equals("c")){
//customer
if(currentUser.isCustomerModeActivation()){
//already filled details
//TODO go to next activity
}else{
//didn't fill details
}
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
Toast.makeText(MainActivity.this, "cancelled", Toast.LENGTH_SHORT).show();
}
};
userDatabaseRefrence.addValueEventListener(valueEventListener);
} else {
// User is signed out
onSignedOutCleanup();
List<AuthUI.IdpConfig> providers = Arrays.asList(
new AuthUI.IdpConfig.Builder(AuthUI.EMAIL_PROVIDER).build(),
new AuthUI.IdpConfig.Builder(AuthUI.GOOGLE_PROVIDER).build());
startActivityForResult(
AuthUI.getInstance()
.createSignInIntentBuilder()
.setIsSmartLockEnabled(false)
.setAvailableProviders(providers)
.setTheme(R.style.LoginTheme)
//.setLogo(R.drawable.ic_melomania_blue_light)
.build(),
RC_SIGN_IN);
//RC request code, it's a flag for when we return rom starting the activity for the results.
}
}
};
}
And Invalidate caches/Restart & Rebuilding the project didn't work.

try changing app gradle to
compileSdkVersion 27
targetSdkVersion 27
compile 'com.android.support:design:27.1.0'
implementation 'com.android.support:appcompat-v7:27.1.0'

Related

Android app running on emulator not on real device

Android emulator is working when running the application but on a real device the app gets an error from the action bar. I am using android bumble bee and the device is a Samsung s21
I already have NoActionBar as well as windowNoTitle true and windowActionBar false
Here is my error
Process: com.example.wonderfinder, PID: 14427
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.wonderfinder/com.example.wonderfinder.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:4166)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:4312)
at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:101)
at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:135)
at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:95)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2571)
at android.os.Handler.dispatchMessage(Handler.java:106)
at android.os.Looper.loopOnce(Looper.java:226)
at android.os.Looper.loop(Looper.java:313)
at android.app.ActivityThread.main(ActivityThread.java:8741)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:571)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1067)
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:581)
at androidx.appcompat.app.AppCompatActivity.setSupportActionBar(AppCompatActivity.java:183)
at com.example.wonderfinder.MainActivity.onCreate(MainActivity.java:46)
at android.app.Activity.performCreate(Activity.java:8578)
at android.app.Activity.performCreate(Activity.java:8557)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1384)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:4147)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:4312) 
at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:101) 
at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:135) 
at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:95) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2571) 
at android.os.Handler.dispatchMessage(Handler.java:106) 
at android.os.Looper.loopOnce(Looper.java:226) 
at android.os.Looper.loop(Looper.java:313) 
at android.app.ActivityThread.main(ActivityThread.java:8741) 
at java.lang.reflect.Method.invoke(Native Method) 
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:571) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1067) 
2022-11-16 13:17:46.765 14427-14427/? I/Process: Sending signal. PID: 14427 SIG: 9
Here is my theme.xml
<resources xmlns:tools="http://schemas.android.com/tools">
<!-- Base application theme. -->
<style name="Theme.WonderFinder" parent="Theme.MaterialComponents.DayNight.NoActionBar">
<item name="colorPrimary">#color/primaryColor</item>
<item name="colorPrimaryVariant">#color/primaryDarkColor</item>
<item name="android:colorPrimaryDark">#color/primaryColor</item>
<item name="colorOnPrimary">#color/white</item>
<!-- Secondary brand color. -->
<item name="colorSecondary">#color/primaryColor</item>
<item name="colorSecondaryVariant">#color/primaryColor</item>
<item name="colorOnSecondary">#color/black</item>
<item name="android:textColorHint">#color/textColor</item>
<item name="windowNoTitle">true</item>
<item name="windowActionBar">false</item>
<item name="android:windowTranslucentStatus">true</item>
<item name="android:windowTranslucentNavigation">true</item>
<!-- Status bar color. -->
<item name="android:statusBarColor" tools:targetApi="l">?attr/colorPrimaryVariant</item>
<item name="android:navigationBarColor">#color/primaryColor</item>
<!-- Customize your theme here. -->
</style>
<style name="ActionBarTheme" parent="Theme.MaterialComponents.DayNight.NoActionBar">
<item name="windowNoTitle">true</item>
<item name="windowActionBar">false</item>
<item name="android:windowTranslucentStatus">true</item>
<item name="android:windowTranslucentNavigation">true</item>
<!-- Primary brand color. -->
<item name="colorPrimary">#color/primaryColor</item>
<item name="colorPrimaryVariant">#color/primaryDarkColor</item>
<item name="android:colorPrimaryDark">#color/primaryColor</item>
<item name="colorOnPrimary">#color/white</item>
<!-- Secondary brand color. -->
<item name="colorSecondary">#color/primaryColor</item>
<item name="colorSecondaryVariant">#color/primaryColor</item>
<item name="colorOnSecondary">#color/black</item>
<item name="android:textColorHint">#color/textColor</item>
<!-- Status bar color. -->
<item name="android:statusBarColor" tools:targetApi="l">?attr/colorPrimaryVariant</item>
<item name="android:navigationBarColor">#color/primaryColor</item>
<!-- Customize your theme here. -->
</style>
</resources>
Here is my main activity
package com.example.wonderfinder;
import androidx.annotation.NonNull;
import androidx.appcompat.app.ActionBarDrawerToggle;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.view.GravityCompat;
import androidx.navigation.NavController;
import androidx.navigation.Navigation;
import androidx.navigation.ui.NavigationUI;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;
import com.bumptech.glide.Glide;
import com.example.wonderfinder.databinding.ActivityMainBinding;
import com.example.wonderfinder.databinding.NavDrawerLayoutBinding;
import com.example.wonderfinder.databinding.ToolbarLayoutBinding;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import de.hdodenhof.circleimageview.CircleImageView;
public class MainActivity extends AppCompatActivity {
//Declare all variables as private variables with their respective types
private NavDrawerLayoutBinding navDrawerLayoutBinding;
private ActivityMainBinding activityMainBinding;
private ToolbarLayoutBinding toolbarLayoutBinding;
private FirebaseAuth firebaseAuth;
private TextView txtName, txtEmail;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
navDrawerLayoutBinding = NavDrawerLayoutBinding.inflate(getLayoutInflater());
setContentView(navDrawerLayoutBinding.getRoot());
//Set the variables to their respective values
activityMainBinding = navDrawerLayoutBinding.mainActivity;
toolbarLayoutBinding = activityMainBinding.toolbar;
setSupportActionBar(toolbarLayoutBinding.toolbar);
firebaseAuth = FirebaseAuth.getInstance();
//Toggle the drawer with open and close
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
this, navDrawerLayoutBinding.navDrawer, toolbarLayoutBinding.toolbar,
R.string.open_navigation_drawer,
R.string.close_navigation_drawer
);
navDrawerLayoutBinding.navDrawer.addDrawerListener(toggle);
toggle.syncState();
NavController navController = Navigation.findNavController(this, R.id.fragmentContainer);
NavigationUI.setupWithNavController(navDrawerLayoutBinding.navigationView, navController);
View headerLayout = navDrawerLayoutBinding.navigationView.getHeaderView(0);
txtName = headerLayout.findViewById(R.id.txtHeaderName);
txtEmail = headerLayout.findViewById(R.id.txtHeaderEmail);
//Call getUserData method
getUserData();
}
//Close the nav the drawer on back pressed
#Override
public void onBackPressed() {
if (navDrawerLayoutBinding.navDrawer.isDrawerOpen(GravityCompat.START))
navDrawerLayoutBinding.navDrawer.closeDrawer(GravityCompat.START);
else
super.onBackPressed();
}
//Method to populate the users username and email in the nav drawer
private void getUserData() {
DatabaseReference databaseReference = FirebaseDatabase.getInstance().getReference("Users")
.child(firebaseAuth.getUid());
databaseReference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
if (snapshot.exists()) {
UserModel userModel = snapshot.getValue(UserModel.class);
txtName.setText(userModel.getUsername());
txtEmail.setText(userModel.getEmail());
}
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});
}
}
I'm going to take a wild stab in the dark here and assume that you are using dark mode (night mode) on your device, but normal (day mode) on the emulator. Am I right??
See some of the answers in this related question: This Activity already has an action bar supplied by the window decor?

change androidx.appcompat.widget.SearchView (Search Icon within Action Bar) for androidx.legacy:legacy-support-v4:1.0.0 using material design

I am stuck on this for days.. I decided to add a bottom navigation, which forced me to change my design to material design. (https://material.io/components/bottom-navigation/android). Several style changes are now messing with my Action Bar. To be more precise, the androidx.appcompat.widget.SearchView of it. As seen in the picture below the search icon is black, I need it to be white.
I have tried a lot of solutions for similar problems answered here, but none seemed to do the trick. My current situation is the following:
I have this menu:
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
android:theme="#style/MyActionBarTheme"
xmlns:app="http://schemas.android.com/apk/res-auto">
<!-- "toolbar top right hand items"-->
<item
android:id="#+id/activityExecutionsMenu_search"
android:icon="#drawable/ic_search_white"
android:title="#string/activityExecutionsFragments_menu_search_hint"
app:actionViewClass="androidx.appcompat.widget.SearchView"
app:showAsAction="always" />
<item
android:id="#+id/activityExecutionsMenu_group"
android:icon="#drawable/ic_group"
android:title="#string/activityExecutionsFragments_menu_group"
app:showAsAction="always"/>
<item
android:id="#+id/activityExecutionsMenu_filter"
android:icon="#drawable/ic_filter"
android:title="#string/activityExecutionsFragments_menu_filter"
app:showAsAction="always"/>
<item
android:id="#+id/activityExecutionsMenu_sort"
android:icon="#drawable/ic_sort"
android:title="#string/activityExecutionsFragments_menu_filter"
app:showAsAction="always"/>
those are the relevant parts of my styles.xml:
<style name="MyActionBarTheme" parent="ThemeOverlay.MaterialComponents.Dark">
<!-- Customize your theme here. -->
<item name="android:actionBarWidgetTheme">#style/MyPopupMenuTheme_withRoundCorners_blue</item>
<item name="actionOverflowMenuStyle">#style/MyPopupMenuTheme_withRoundCorners_blue</item>
<item name="android:textAppearanceLargePopupMenu">#style/myPopupMenuTextAppearanceLarge
</item>
<item name="android:textAppearanceSmallPopupMenu">#style/myPopupMenuTextAppearanceSmall
</item>
<item name="actionMenuTextColor">#color/white</item>
<!--<item name="colorControlNormal">#color/stress10</item>-->
<item name="colorPrimary">#color/colorPrimary</item>
<item name="colorPrimaryDark">#color/colorPrimaryDark</item>
<item name="colorAccent">#color/colorPrimary</item>
<!--<item name="android:textColorSecondary">#color/mood6</item>-->
<item name="android:windowBackground">#color/backgroundColor</item>
<item name="popupMenuStyle">#style/MyPopupMenuTheme_withRoundCorners_blue</item>
<item name="android:popupMenuStyle">#style/MyPopupMenuTheme_withRoundCorners_blue</item>
<!--<item name="android:actionBarStyle">#style/MyTheme.ActionBarStyle</item>-->
<item name="android:actionButtonStyle">#style/myActionButtonStyle</item>
<item name="actionButtonStyle">#style/myActionButtonStyle</item>
</style>
<style name="myActionButtonStyle" parent="Widget.MaterialComponents.FloatingActionButton">
<item name="android:minWidth">30dp</item>
<item name="android:maxWidth">48dp</item>
<item name="android:width">36dp</item>
</style>
<style name="myPopupMenuTextAppearanceSmall" parent="#style/MaterialAlertDialog.MaterialComponents.Title.Text">
<item name="android:textColor">#color/colourAsLinkIndicatingAction</item>
</style>
<style name="myPopupMenuTextAppearanceLarge" parent="#style/MaterialAlertDialog.MaterialComponents.Title.Text">
<item name="android:textColor">#color/colourAsLinkIndicatingAction</item>
</style>
<style name="MyPopupMenuTheme_withRoundCorners" parent="Theme.MaterialComponents.Light.NoActionBar">
<item name="colorPrimary">#color/colorPrimary</item>
<item name="colorPrimaryDark">#color/colorPrimaryDark</item>
<item name="colorAccent">#color/colorPrimary</item>
<item name="android:textAppearanceLargePopupMenu">#style/myPopupMenuTextAppearanceLarge
</item>
<item name="android:textAppearanceSmallPopupMenu">#style/myPopupMenuTextAppearanceSmall
</item>
<item name="android:tint">#color/colourAsLinkIndicatingAction</item>
<item name="android:textColor">#color/colourAsLinkIndicatingAction</item>
<item name="android:popupMenuStyle">#drawable/rounded_corners_background_for_popupmenu</item>
<item name="android:popupBackground">#drawable/rounded_corners_background_for_popupmenu</item>
<item name="popupMenuStyle">#drawable/rounded_corners_background_for_popupmenu</item>
<item name="background">#drawable/rounded_corners_background_for_popupmenu</item>
<item name="android:colorBackground">#color/colourAsLinkIndicatingAction</item>
</style>
<style name="MyPopupMenuTheme_withRoundCorners_blue" parent="Theme.MaterialComponents.Light.NoActionBar">
<item name="colorPrimary">#color/colorPrimary</item>
<item name="colorPrimaryDark">#color/colorPrimaryDark</item>
<item name="colorAccent">#color/colorPrimary</item>
<item name="android:textAppearanceLargePopupMenu">#style/myPopupMenuTextAppearanceLarge
</item>
<item name="android:textAppearanceSmallPopupMenu">#style/myPopupMenuTextAppearanceSmall
</item>
<item name="android:textColor">#color/colourAsLinkIndicatingAction</item>
<item name="android:popupMenuStyle">#drawable/rounded_corners_background_for_popupmenu_blue</item>
<item name="android:popupBackground">#drawable/rounded_corners_background_for_popupmenu_blue</item>
<item name="popupMenuStyle">#drawable/rounded_corners_background_for_popupmenu_blue</item>
<item name="background">#drawable/rounded_corners_background_for_popupmenu_blue</item>
<item name="android:colorBackground">#color/colourAsLinkIndicatingAction</item>
</style>
This is the Fragment, that gets reused in several parts of my app which creates the menu, including the onCreateOptionsMenu, in which some other promising attempts of SO answers seemed to get the job done, but do not work for me
...
import android.app.SearchManager;
...
import import androidx.appcompat.widget.SearchView;
...
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import androidx.fragment.app.DialogFragment;
import androidx.fragment.app.FragmentManager;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
...
public class ActivityExecutions_Fragment
extends DialogFragment
{
public View view;
private Toolbar myToolbar;
public SearchView searchView;
...
/*
* empty constructor
*/
public ActivityExecutions_Fragment(){}
/*
* use this to instantiate fragment
*
* pass parameters to individualize behaviour
*/
public static ActivityExecutions_Fragment newInstance(String source)
{
ActivityExecutions_Fragment frag = new ActivityExecutions_Fragment();
Bundle args = new Bundle();
args.putString("source", source);
frag.setArguments(args);
return frag;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState)
{
FrameLayout frameLayout = new FrameLayout(getActivity());
...
populateViewForOrientation(inflater, frameLayout);
return frameLayout;
}
/*
* remove title bar
*/
#Override
public Dialog onCreateDialog(Bundle savedInstanceState)
{
Dialog dialog = super.onCreateDialog(savedInstanceState);
// request a window without the title
dialog.getWindow().requestFeature(Window.FEATURE_NO_TITLE);
return dialog;
}
/**
similar behaviour as onCreate() in activities
adjusted for fragments
*/
private void populateViewForOrientation(LayoutInflater inflater, ViewGroup viewGroup)
{
viewGroup.removeAllViewsInLayout();
if(deviceIsCurrentlyInPortraitOrientation)
{
view = inflater.inflate(R.layout.activity_executions_fragment, viewGroup);
}
else
{
view = inflater.inflate(R.layout.activity_executions_fragment, viewGroup);
}
...
myToolbar = (Toolbar) view.findViewById(R.id.toolbar_activityExecutions);
getActivity().getSupportActionBar().setHomeAsUpIndicator(R.drawable.ic_close_white);
getActivity().getSupportActionBar().setHomeButtonEnabled(true);
getActivity().getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getActivity().getSupportActionBar().setDisplayShowHomeEnabled(true);
}
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
menu.clear();
inflater.inflate(R.menu.activity_executions_menu, menu);
super.onCreateOptionsMenu(menu,inflater);
searchView = (SearchView)menu.findItem(R.id.activityExecutionsMenu_search).getActionView();
searchView.setMaxWidth(Integer.MAX_VALUE);
// this attempt does not work icon stays black
ImageView searchIcon=
searchView.findViewById(androidx.appcompat.R.id.search_mag_icon);
searchIcon.setColorFilter(getResources().getColor(R.color.white),
android.graphics.PorterDuff.Mode.SRC_IN);
);
}
#Override
public void onPrepareOptionsMenu(Menu menu) {
super.onPrepareOptionsMenu(menu);
menu.findItem(R.id.activityExecutionsMenu_group).setIcon(R.drawable.ic_ungroup);
toolbar_searchButton = menu.findItem(R.id.activityExecutionsMenu_search);
toolbar_groupButton = menu.findItem(R.id.activityExecutionsMenu_group);
toolbar_filterButton = menu.findItem(R.id.activityExecutionsMenu_filter);
toolbar_sortButton = menu.findItem(R.id.activityExecutionsMenu_sort);
}
}
And these are some dependencies used in my gradle file
implementation "androidx.work:work-runtime:2.5.0"
implementation 'androidx.constraintlayout:constraintlayout:2.0.4'
testImplementation 'junit:junit:4.12'
implementation 'androidx.appcompat:appcompat:1.2.0'
implementation 'com.google.android.material:material:1.2.1'
implementation 'com.google.firebase:firebase-appindexing:19.1.0'
implementation 'androidx.legacy:legacy-support-v4:1.0.0'
implementation 'com.googlecode.mp4parser:isoparser:1.1.21'
implementation 'com.github.bumptech.glide:glide:4.9.0'
annotationProcessor 'com.github.bumptech.glide:compiler:4.9.0'
implementation 'androidx.palette:palette:1.0.0'
How do I manage to get the search icon to be white again?
Should I remove the legacy.support library? Are there too many corresponding dependencies? Is it an issue extending DialogFragment?

Customizing a DialogFragment

The first image is what I want. The second is what I get
I've this class to create a dialog
import android.app.AlertDialog;
import android.app.Application;
import android.app.Dialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.support.v4.app.DialogFragment;
import android.widget.Toast;
public class AlertFragment extends DialogFragment {
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
return new AlertDialog.Builder(getActivity())
// Set Dialog Icon
.setIcon(R.drawable.androidhappy)
// Set Dialog Title
.setTitle("Alert DialogFragment")
// Set Dialog Message
.setMessage("Alert DialogFragment Tutorial")
// Positive button
.setPositiveButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
})
// Negative Button
.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// Do something else
}
}).create();
}
}
In my view
import android.support.v4.app.DialogFragment;
import android.support.v4.app.FragmentManager;
import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.support.v7.app.AlertDialog;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.VolleyLog;
import com.android.volley.toolbox.JsonObjectRequest;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
.......
final FragmentManager fm = getSupportFragmentManager();
.......
AlertFragment alertdFragment = new AlertFragment();
// Show Alert DialogFragment
alertdFragment.setStyle(DialogFragment.STYLE_NORMAL, R.style.MyDialogFragmentStyle);
alertdFragment.show(fm, "Alert Dialog Fragment");
This is my style file
<resources>
<!-- Base application theme. -->
<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>
<item name="android:spinnerItemStyle">
#style/spinnerItemStyle
</item>
<!-- For each individual Spinner list item once clicked on -->
<item name="android:spinnerDropDownItemStyle">
#style/spinnerDropDownItemStyle
</item>
</style>
<style name="AppTheme.NoActionBar">
<item name="windowActionBar">false</item>
<item name="windowNoTitle">true</item>
</style>
<style name="AppTheme.AppBarOverlay" parent="ThemeOverlay.AppCompat.Dark.ActionBar" />
<style name="AppTheme.PopupOverlay" parent="ThemeOverlay.AppCompat.Light" />
<style name="spinnerItemStyle" parent="#android:style/Widget.Holo.DropDownItem.Spinner">
<item name="android:padding">0dp</item>
<item name="android:textSize">#dimen/fld_txt_size</item>
</style>
<style name="spinnerDropDownItemStyle">
<item name="android:padding">0dp</item>
<item name="android:textSize">#dimen/fld_txt_size</item>
</style>
<style name="AppTheme.Button" parent="Widget.AppCompat.Button.Colored">
<item name="android:textColor">#color/btn_text</item>
</style>
<style name="MyDialogFragmentStyle" parent="Theme.AppCompat.Light.Dialog.Alert">
<item name="windowActionBar">true</item>
<item name="windowNoTitle">false</item>
<item name="android:windowActionBar">false</item>
<item name="android:windowNoTitle">false</item>
<item name="android:headerDividersEnabled">true</item>
</style>
</resources>
I've posted all the style to see if there's anything going wrong. Regardless that I would like the separator between the header and the body of the dialog I do not understand why the buttons do not appear.
Edit:
I read this
Missing buttons on AlertDialog | Android 7.0 (Nexus 5x)
and I realized that i need to define a style for my dialog.
Infact if i set this
<style name="AlertDialogTheme" parent="Theme.AppCompat.Light.Dialog.Alert">
<item name="colorPrimary">#color/colorPrimary</item>
<item name="colorPrimaryDark">#color/colorPrimaryDark</item>
<item name="colorAccent">#color/colorAccent</item>
<item name="windowActionBar">true</item>
<item name="windowNoTitle">false</item>
<item name="android:buttonBarStyle">#style/Widget.AppCompat.ActionButton</item>
</style>
and then initialize dialog in this way
AlertDialog.Builder builder = new AlertDialog.Builder(SettingActivity.this,R.style.dialog_theme);
I can see change of color and text. But wich is property to show title, separator and buttons?
if you want a customized layout. You need to create an instance of Dialog. i.e. Dialog dialog = new Dialog; and set the contentview for that dialog: dialog.setContentView(R.layout.my_customized_dialog_layout);
you can then create buttons inside that layout and initialize them.

onClick event of button not working android

I'm trying to implement Guillotine Menu by yalantis in my app.
I've put one button in the guillotine activity and have made a class for the guillotine activity. In that class I'm trying to implement the listener for the button .I've also a put a toast in that function but that's not getting displayed either.
Here is the guillotine activity:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#color/guillotine_background"
android:orientation="vertical">
<ScrollView
android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#color/guillotine_background"
android:layout_margin = "0dp"
android:divider="#666"
android:orientation="vertical" >
<android.support.v7.widget.Toolbar
style="#style/Toolbar"
app:contentInsetStart="0dp">
<ImageView
android:id="#+id/guillotine_hamburger"
style="#style/ImageView.Hamburger"
android:src="#drawable/ic_menu" />
</android.support.v7.widget.Toolbar>
<LinearLayout
android:id="#+id/profile_group"
style="#style/LinearLayout.GuillotineItem"
android:layout_marginTop="#dimen/guillotine_medium_margin">
<ImageView
style="#style/ImageView.GuillotineItem"
android:src="#drawable/ic_profile" />
<Button
style="#style/TextView.GuillotineItem"
android:text="MAIN PAGE"
android:background="#color/guillotine_background"
android:id="#+id/b1"
/>
</LinearLayout>
<LinearLayout
android:id="#+id/feed_group"
style="#style/LinearLayout.GuillotineItem">
<ImageView
style="#style/ImageView.GuillotineItem"
android:src="#drawable/ic_feed" />
<TextView
style="#style/TextView.GuillotineItem"
android:text="#string/feed" />
</LinearLayout>
<LinearLayout
android:id="#+id/activity_group"
style="#style/LinearLayout.GuillotineItem">
<ImageView
style="#style/ImageView.GuillotineItem"
android:src="#drawable/ic_activity_active" />
<TextView
style="#style/TextView.GuillotineItem.Selected"
android:text="#string/activity" />
</LinearLayout>
<View
android:layout_width="match_parent"
android:layout_height="#dimen/guillotine_divider_height" />
<LinearLayout
android:id="#+id/settings_group"
style="#style/LinearLayout.GuillotineItem">
<ImageView
style="#style/ImageView.GuillotineItem"
android:src="#drawable/ic_settings" />
<TextView
style="#style/TextView.GuillotineItem"
android:text="#string/settings" />
</LinearLayout>
</LinearLayout>
</ScrollView>
</LinearLayout>
And here is the class:
package manipal.freshers;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.view.View.OnClickListener;
import android.widget.Toast;
import java.io.File;
/**
* Created by Ankit Vimal on 28-02-2016.
*/
public class Guillotine extends AppCompatActivity {
private Button b1;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.guillotine);
b1=(Button)findViewById(R.id.b1);
b1.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
Toast.makeText(getBaseContext(), "a", Toast.LENGTH_LONG).show();
Intent i = new Intent(Guillotine.this, MIT_Sports_Club_Activity.class);
startActivity(i);
}
}
);
}
}
Styles.xml:
<resources>
<style name="LinearLayout" />
<style name="LinearLayout.GuillotineItem">
<item name="android:layout_width">match_parent</item>
<item name="android:layout_height">wrap_content</item>
<item name="android:orientation">horizontal</item>
<item name="android:layout_marginTop">#dimen/guillotine_small_margin</item>
</style>
<style name="TextView" />
<style name="TextView.ToolbarTitle">
<item name="android:gravity">center</item>
<item name="android:textSize">24sp</item>
<item name="android:layout_width">match_parent</item>
<item name="android:layout_height">wrap_content</item>
</style>
<style name="TextView.GuillotineItem">
<item name="android:layout_width">wrap_content</item>
<item name="android:layout_height">wrap_content</item>
<item name="android:layout_marginLeft">#dimen/guillotine_small_margin</item>
<item name="android:textSize">#dimen/guillotine_item_text_size</item>
<item name="android:layout_gravity">center_vertical</item>
<item name="android:textColor">#android:color/white</item>
</style>
<style name="TextView.GuillotineItem.Selected">
<item name="android:textColor">#color/selected_item_color</item>
</style>
<style name="Toolbar">
<item name="android:layout_height">wrap_content</item>
<item name="android:layout_width">match_parent</item>
<item name="android:minHeight">?attr/actionBarSize</item>
<item name="android:windowNoTitle">true</item>
<item name="android:background">#color/guillotine_background</item>
</style>
<style name="ImageView" />
<style name="ImageView.ContentItem">
<item name="android:layout_height">wrap_content</item>
<item name="android:layout_width">match_parent</item>
</style>
<style name="ImageView.Hamburger" parent="Widget.AppCompat.ActionButton">
<item name="android:layout_height">wrap_content</item>
<item name="android:layout_width">wrap_content</item>
<item name="android:layout_marginBottom">#dimen/abc_action_bar_overflow_padding_start_material</item>
</style>
<style name="ImageView.GuillotineItem">
<item name="android:layout_width">wrap_content</item>
<item name="android:layout_height">wrap_content</item>
<item name="android:layout_gravity">center_vertical</item>
<item name="android:layout_marginLeft">#dimen/guillotine_large_margin</item>
</style>
</resources>
Themes.xml:
<?xml version="1.0" encoding="utf-8"?>
<resources>
<style name="AppTheme" parent="Theme.Guillotine"/>
<style name="Theme.Guillotine" parent="Theme.AppCompat.NoActionBar">
<item name="android:color">#color/guillotine_background</item>
<item name="android:windowContentOverlay">#null</item>
<item name="android:windowNoTitle">true</item>
<item name="android:colorPrimaryDark">#color/guillotine_background</item>
<item name="android:colorPrimary">#color/guillotine_background_dark</item>
<item name="android:windowActionBar">false</item>
<item name="windowActionBar">false</item>
</style>
</resources>
MainActivity.java:
package manipal.freshers;
import android.annotation.SuppressLint;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.text.method.ScrollingMovementMethod;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import butterknife.ButterKnife;
import butterknife.InjectView;
import com.yalantis.guillotine.animation.GuillotineAnimation;
public class MainActivity extends AppCompatActivity {
private static final long RIPPLE_DURATION = 250;
#InjectView(R.id.toolbar)
Toolbar toolbar;
#InjectView(R.id.root)
FrameLayout root;
#InjectView(R.id.content_hamburger)
View contentHamburger;
private String[] drawerListViewItems;
private DrawerLayout drawerLayout;
private ListView drawerListView;
private TextView t;
int []imageArray={R.drawable.manipal1,R.drawable.manipal2,R.drawable.manipal3,R.drawable.manipal4,R.drawable.manipal5};
private ImageView i1;
private final Handler handler = new Handler();
#SuppressLint("NewApi")
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ButterKnife.inject(this);
i1=(ImageView) findViewById(R.id.imageView1);
t = (TextView) findViewById(R.id.textView3);
t.setMovementMethod(new ScrollingMovementMethod());
if(toolbar!= null){
if (android.os.Build.VERSION.SDK_INT >= 11){
setSupportActionBar(toolbar);
getSupportActionBar().setTitle(null);
}}
View guillotineMenu = LayoutInflater.from(this).inflate(R.layout.guillotine, null);
root.addView(guillotineMenu);
new GuillotineAnimation.GuillotineBuilder(guillotineMenu, guillotineMenu.findViewById(R.id.guillotine_hamburger), contentHamburger)
.setStartDelay(RIPPLE_DURATION)
.setActionBarViewForAnimation(toolbar)
.setClosedOnStart(true)
.build();
Runnable runnable = new Runnable() {
int i=0;
public void run()
{
i1.setImageResource(imageArray[i]);
i++;
if(i>imageArray.length-1)
{
i=0;
}
handler.postDelayed(this, 3000); //for interval...
}
};
handler.postDelayed(runnable,0);
}
}
package com.example.vinaymaneti.button;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
private Button b1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
b1 = (Button) findViewById(R.id.b1);
b1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(getApplicationContext(), "Hello", Toast.LENGTH_SHORT).show();
}
});
}
}

Define TabLayout style in theme

I have two different styles of TabLayout in my app:
<style name="TabLayoutPower" parent="Widget.Design.TabLayout">
<item name="tabSelectedTextColor">#android:color/white</item>
<item name="tabTextColor">#android:color/white</item>
</style>
<style name="TabLayoutFree" parent="Widget.Design.TabLayout">
<item name="tabSelectedTextColor">#android:color/black</item>
<item name="tabTextColor">#android:color/black</item>
</style>
How can I define the default TabLayout style for a theme? I cannot find any info which item name should I use to build my theme. I'd like to add the TabLayout the same way I added my listview:
<style name="Free" parent="Theme.AppCompat.Light.DarkActionBar">
<item name="colorPrimary">#color/black</item>
<item name="colorPrimaryDark">#color/black</item>
<item name="colorAccent">#color/main_red</item>
<item name="android:windowBackground">#color/main_bg_light</item>
<item name="android:listViewStyle">#style/MyListView</item>
</style>
For Support Library TabLayout, you can set tabStyle attribute in your theme:
<style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
<!-- ... -->
<item name="tabStyle">#style/AppTheme.TabLayout</item>
</style>
<style name="AppTheme.TabLayout" parent="Widget.Design.TabLayout">
<item name="tabSelectedTextColor">#android:color/white</item>
<item name="tabTextColor">#android:color/white</item>
</style>
If you wan to use 2 different styles for your TabLayout based on theme of your application then you should define your style inside attrs.xml
here is the Sample code for that
First you create an attrs.xml file ( Like this )
<?xml version="1.0" encoding="utf-8"?>
<resources>
<attr name="textColor" format="reference|color" />
<attr name="backColor" format="reference|color" />
<attr name="myTabStyle" format="reference" />
</resources>
define various theme as per your requirements inside styles.xml
Note: i have used 3 different themes for demo
<resources>
<!-- Base application theme. -->
<style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
<item name="colorPrimary">#color/colorPrimary</item>
<item name="colorPrimaryDark">#color/colorPrimaryDark</item>
<item name="colorAccent">#color/colorAccent</item>
<item name="tabStyle">#style/TabLayoutPower</item>
<item name="textColor">#android:color/white</item>
<item name="backColor">#color/colorPrimary</item>
</style>
<style name="AppTheme2" parent="Theme.AppCompat.Light.DarkActionBar">
<item name="colorPrimary">#android:color/holo_green_dark</item>
<item name="colorPrimaryDark">#android:color/white</item>
<item name="colorAccent">#android:color/holo_blue_dark</item>
<item name="textColor">#android:color/white</item>
<item name="tabStyle">#style/TabLayoutFree</item>
<item name="backColor">#FF00</item>
</style>
<style name="AppTheme3" parent="Theme.AppCompat.Light.DarkActionBar">
<item name="colorPrimary">#ff00</item>
<item name="colorPrimaryDark">#ff0</item>
<item name="colorAccent">#0a91d4</item>
<item name="tabStyle">#style/TabLayoutNew</item>
<item name="textColor">#FF00</item>
<item name="backColor">#android:color/white</item>
</style>
<style name="TabLayoutPower" parent="Widget.Design.TabLayout">
<item name="tabSelectedTextColor">#android:color/white</item>
<item name="tabTextColor">#android:color/white</item>
</style>
<style name="TabLayoutFree" parent="Widget.Design.TabLayout">
<item name="tabSelectedTextColor">#android:color/holo_blue_bright</item>
<item name="tabTextColor">#android:color/holo_blue_bright</item>
</style>
<style name="TabLayoutNew" parent="Widget.Design.TabLayout">
<item name="tabSelectedTextColor">#android:color/holo_green_dark</item>
<item name="tabTextColor">#android:color/holo_green_dark</item>
</style>
</resources>
Now use this style in your TabLayout like this inside layout.xml files
Use like this style="?myTabStyle" it will select style based on current theme of your application
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<Button
android:id="#+id/btnThemeOne"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="Theme One" />
<Button
android:id="#+id/btnThemeTwo"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="Theme Two" />
<Button
android:id="#+id/btnThemeThree"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="Theme Three" />
</LinearLayout>
<android.support.design.widget.TabLayout
android:id="#+id/tabs"
style="?myTabStyle"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:tabGravity="fill"
android:background="#color/colorAccent"
app:tabMode="fixed" />
<android.support.v4.view.ViewPager
android:id="#+id/viewpager"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_behavior="#string/appbar_scrolling_view_behavior" />
</LinearLayout>
sample code of TabsActivity to change theme
import android.os.Bundle;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.List;
public class TabsActivity extends AppCompatActivity {
PrefManager prefManager;
private TabLayout tabLayout;
private ViewPager viewPager;
private Button btnThemeOne, btnThemeTwo, btnThemeThree;
#Override
protected void onCreate(Bundle savedInstanceState) {
prefManager = new PrefManager(this);
getTheme().applyStyle(prefManager.getTheme(), true);
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_tabs);
btnThemeOne = findViewById(R.id.btnThemeOne);
btnThemeOne.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Toast.makeText(TabsActivity.this, "Applying theme one", Toast.LENGTH_SHORT).show();
prefManager.setTheme(R.style.AppTheme);
recreate();
}
});
btnThemeTwo = findViewById(R.id.btnThemeTwo);
btnThemeTwo.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Toast.makeText(TabsActivity.this, "Applying theme two", Toast.LENGTH_SHORT).show();
prefManager.setTheme(R.style.AppTheme2);
recreate();
}
});
btnThemeThree = findViewById(R.id.btnThemeThree);
btnThemeThree.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Toast.makeText(TabsActivity.this, "Applying theme three", Toast.LENGTH_SHORT).show();
prefManager.setTheme(R.style.AppTheme3);
recreate();
}
});
viewPager = findViewById(R.id.viewpager);
setupViewPager(viewPager);
tabLayout = findViewById(R.id.tabs);
tabLayout.setupWithViewPager(viewPager);
}
private void setupViewPager(ViewPager viewPager) {
ViewPagerAdapter adapter = new ViewPagerAdapter(getSupportFragmentManager());
adapter.addFragment(new OneFragment(), "ONE");
adapter.addFragment(new OneFragment(), "TWO");
adapter.addFragment(new OneFragment(), "THREE");
viewPager.setAdapter(adapter);
}
class ViewPagerAdapter extends FragmentPagerAdapter {
private final List<Fragment> mFragmentList = new ArrayList<>();
private final List<String> mFragmentTitleList = new ArrayList<>();
public ViewPagerAdapter(FragmentManager manager) {
super(manager);
}
#Override
public Fragment getItem(int position) {
return mFragmentList.get(position);
}
#Override
public int getCount() {
return mFragmentList.size();
}
public void addFragment(Fragment fragment, String title) {
mFragmentList.add(fragment);
mFragmentTitleList.add(title);
}
#Override
public CharSequence getPageTitle(int position) {
return mFragmentTitleList.get(position);
}
}
}
PrefManager class to save theme info
import android.content.Context;
import android.content.SharedPreferences;
public class PrefManager {
// Shared preferences file name
private final String PREF_NAME = "theme-pref";
private final String THEME = "theme";
SharedPreferences pref;
SharedPreferences.Editor editor;
public PrefManager(Context context) {
pref = context.getSharedPreferences(PREF_NAME, 0);
editor = pref.edit();
}
public int getTheme() {
return pref.getInt(THEME, R.style.AppTheme);
}
public void setTheme(int themeId) {
editor.putInt(THEME, themeId);
editor.commit();
}
}
you can check the output video of above code
https://www.youtube.com/watch?v=uup072IDGd0
You can find that name in Android theme -
<item name="android:tabWidgetStyle">#style/Your.Style</item>
<style name="Base.Widget.Design.TabLayout" parent="">
<item name="tabSelectedTextColor">#android:color/white</item>
<item name="tabTextColor">#android:color/white</item>
</style>
<style name="Free" parent="Theme.AppCompat.Light.DarkActionBar">
<item name="colorPrimary">#color/black</item>
<item name="colorPrimaryDark">#color/black</item>
<item name="colorAccent">#color/main_red</item>
<item name="android:windowBackground">#color/main_bg_light</item>
<item name="android:listViewStyle">#style/MyListView</item>
<item name="android:tabWidgetStyle">#style/Base.Widget.Design.TabLayout</item>
</style>

Categories

Resources