CollapsingToolbarLayout not visible when specific fragment is active? - android

I have only one activity in my project and that is MainActivity and I have implemented a collapsing toolbar layout on my MainActivity's layout:
activity_main.xml:
<?xml version="1.0" encoding="utf-8"?>
<layout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:ads="http://schemas.android.com/apk/res-auto"
xmlns:app="http://schemas.android.com/apk/res-auto">
<androidx.coordinatorlayout.widget.CoordinatorLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<com.google.android.material.appbar.AppBarLayout
android:id="#+id/app_bar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:fitsSystemWindows="true"
android:theme="#style/Theme">
<com.google.android.material.appbar.CollapsingToolbarLayout
android:id="#+id/toolbar_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
ads:expandedTitleMarginBottom="24dp"
ads:expandedTitleMargin="16dp"
app:layout_scrollFlags="scroll|exitUntilCollapsed|snap">
<androidx.appcompat.widget.AppCompatImageView
android:id="#+id/app_bar_img"
android:layout_width="match_parent"
android:layout_height="200dp"
android:scaleType="centerCrop"
ads:srcCompat="#mipmap/logo"
ads:layout_collapseMode="parallax"
ads:layout_collapseParallaxMultiplier="#integer/material_motion_duration_long_2" />
<androidx.appcompat.widget.Toolbar
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
ads:layout_collapseMode="pin"
ads:popupTheme="#style/Widget.AppCompat.PopupMenu.Overflow" />
</com.google.android.material.appbar.CollapsingToolbarLayout>
</com.google.android.material.appbar.AppBarLayout>
<androidx.fragment.app.FragmentContainerView
android:id="#+id/container"
android:name="androidx.navigation.fragment.NavHostFragment"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:defaultNavHost="true"
app:navGraph="#navigation/nav_graph" />
</androidx.coordinatorlayout.widget.CoordinatorLayout>
</layout>
and I wanted the toolbar to be visible only when a few specific fragments are active on the screen and to achieve that functionality, I've implemented the logic like this:
BaseActivity.kt:
open class BaseActivity : AppCompatActivity()
MainActivity.kt:
package com.pavan.teja.example
import android.os.Bundle
import android.view.Menu
import android.view.MenuItem
import android.view.View
import android.view.WindowManager
import androidx.core.text.HtmlCompat
import androidx.databinding.DataBindingUtil
import androidx.navigation.NavController
import androidx.navigation.NavDestination
import androidx.navigation.fragment.findNavController
import com.google.android.material.appbar.AppBarLayout
import com.pavan.teja.example.BaseApplicationStuff.BaseActivity
import com.pavan.teja.example.Utils.Utilities
import com.pavan.teja.example.databinding.ActivityMainBinding
import kotlinx.android.synthetic.main.activity_main.view.*
import timber.log.Timber
class MainActivity : BaseActivity(), AppBarLayout.OnOffsetChangedListener, NavController.OnDestinationChangedListener {
private lateinit var utilities: Utilities
private lateinit var activityMainBinding: ActivityMainBinding
private var navController: NavController? = null
private lateinit var appToolbar: androidx.appcompat.widget.Toolbar
private lateinit var appBarLayout: AppBarLayout
private lateinit var menu: Menu
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
activityMainBinding = DataBindingUtil.setContentView(this, R.layout.activity_main)
utilities = Utilities()
//Apply security by blocking screenshots
window.setFlags(
WindowManager.LayoutParams.FLAG_SECURE,
WindowManager.LayoutParams.FLAG_SECURE
)
//Setting up AppBar
appToolbar = activityMainBinding.toolbar
//setting AppBar Layout
appBarLayout = activityMainBinding.appBar
appBarLayout.addOnOffsetChangedListener(this)
setSupportActionBar(appToolbar)
//Fragment Navigation setup
val navHostFragment =
supportFragmentManager.findFragmentById(activityMainBinding.container.id)
navController = navHostFragment?.findNavController()
navController?.addOnDestinationChangedListener(this)
}
override fun onOffsetChanged(appBarLayout: AppBarLayout?, verticalOffset: Int) {
var isShow = false
var scrollRange = -1
if (scrollRange == -1) {
scrollRange = appBarLayout?.totalScrollRange!!
}
if (scrollRange + verticalOffset == 0) {
isShow = true
// showOption(R.id.action_info)
} else if (isShow) {
isShow = false
// hideOption(R.id.action_info)
}
}
override fun onCreateOptionsMenu(menu: Menu?): Boolean {
menuInflater.inflate(R.menu.memu, menu)
if (menu != null) {
this.menu = menu
}
return true
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
when (item.itemId) {
}
return super.onOptionsItemSelected(item)
}
private fun hideOption(id: Int) {
val item: MenuItem = menu.findItem(id)
item.isVisible = false
}
private fun showOption(id: Int) {
val item: MenuItem = menu.findItem(id)
item.isVisible = true
}
override fun onSupportNavigateUp(): Boolean {
return navController!!.navigateUp()
}
override fun onDestinationChanged(controller: NavController,
destination: NavDestination,
arguments: Bundle?
) {
when (navController?.currentDestination?.label) {
"SplashScreenFragment" -> {
activityMainBinding.appBar.visibility = View.GONE
// supportActionBar?.hide()
activityMainBinding.container.fitsSystemWindows = true
utilities.hideSystemUI(window, activityMainBinding.root)
}
"InitiationCheckFragment" -> {
activityMainBinding.appBar.visibility = View.GONE
// supportActionBar?.hide()
activityMainBinding.container.fitsSystemWindows = true
utilities.hideSystemUI(window, activityMainBinding.root)
}
"NotInitiatedFragment" -> {
activityMainBinding.appBar.visibility = View.GONE
// supportActionBar?.hide()
activityMainBinding.container.fitsSystemWindows = true
utilities.hideSystemUI(window, activityMainBinding.root)
}
else -> {
// activityMainBinding.container.fitsSystemWindows = false
supportActionBar?.show()
supportActionBar?.setDisplayHomeAsUpEnabled(true)
supportActionBar?.setDisplayShowHomeEnabled(true)
supportActionBar?.title = getString(R.string.app_bar_title)
// val title = getString(R.string.app_bar_title)
// appToolbar.toolbar.title = title
// appToolbar.showOverflowMenu()
// supportActionBar?.title =
// HtmlCompat.fromHtml("<big>${title}</big>", HtmlCompat.FROM_HTML_MODE_LEGACY)
// activityMainBinding.container.fitsSystemWindows = false
utilities.showSystemUI(window, activityMainBinding.root)
}
}
Timber.d("current active fragment ${navController?.currentDestination?.label}")
}
}
Here's the Utilities class code:
class Utilities {
fun hideSystemUI(window: Window, mainContainer: View) {
WindowCompat.setDecorFitsSystemWindows(window, false)
WindowInsetsControllerCompat(window, mainContainer).let { controller ->
controller.hide(WindowInsetsCompat.Type.systemBars())
controller.systemBarsBehavior =
WindowInsetsControllerCompat.BEHAVIOR_SHOW_TRANSIENT_BARS_BY_SWIPE
}
}
fun showSystemUI(window: Window, mainContainer: View) {
WindowCompat.setDecorFitsSystemWindows(window, true)
WindowInsetsControllerCompat(
window,
mainContainer
).show(WindowInsetsCompat.Type.systemBars())
}
themes.xml:
<resources xmlns:tools="http://schemas.android.com/tools">
<!-- Base application theme. -->
<style name="Theme.MyCustomAppTheme" parent="Theme.MaterialComponents.DayNight.NoActionBar">
<!-- Primary brand color. -->
<item name="colorPrimary">#f21505</item>
<item name="colorPrimaryVariant">#ed594e</item>
<item name="colorOnPrimary">#color/white</item>
<!-- Secondary brand color. -->
<item name="colorSecondary">#f25c05</item>
<item name="colorSecondaryVariant">#f58b4e</item>
<!-- <item name="colorOnSecondary">#color/black</item>-->
<!-- Status bar color. -->
<item name="android:statusBarColor" tools:targetApi="l">?attr/colorPrimaryVariant</item>
<!-- Customize your theme here. -->
</style>
</resources>
night/themes.xml:
<resources xmlns:tools="http://schemas.android.com/tools">
<!-- Base application theme. -->
<style name="Theme.MyCustomAppTheme" parent="Theme.MaterialComponents.DayNight.NoActionBar">
<!-- Primary brand color. -->
<item name="colorPrimary">#f21505</item>
<item name="colorPrimaryVariant">#ed594e</item>
<item name="colorOnPrimary">#color/white</item>
<!-- Secondary brand color. -->
<item name="colorSecondary">#f25c05</item>
<item name="colorSecondaryVariant">#f58b4e</item>
<!-- <item name="colorOnSecondary">#color/black</item>-->
<!-- Status bar color. -->
<item name="android:statusBarColor" tools:targetApi="l">?attr/colorPrimaryVariant</item>
<!-- Customize your theme here. -->
</style>
</resources>
The app doesn't crash but it doesn't show the app bar when the fragments where I wanted the appbar to be visible.
Now that the toolbar layout is on MainActivity, I haven't implemented anything on the fragments regarding the toolbar. I'm changing the fragments using navController.
Can anyone please help me resolve this problem and make the appbar visible on top of the fragments?
Thank you.

Related

status bar becoming black and icon visible on swiping in Android api 30

I am using fragment and in that fragment i have ViewPager and in ViewPager i have added two fragments.when i open the app Everything works fine but my status bar becomes black and to see the icon i need to scroll down and this is happening in android 11,below android 11 Eveything working fine.now please let me know how to fix it...please don't ignore this and answer should be in Kotlin if Possible
I am attaching the code for it also
Main Activity:
class dashact : AppCompatActivity() {
lateinit var toolbar: Toolbar
lateinit var coordinator: CoordinatorLayout
lateinit var navigationdrawer: NavigationView
lateinit var drawerLayout: DrawerLayout
var nameofuser :String?="jdghjg"
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.dashact)
toolbar = findViewById(R.id.toolbar)
coordinator = findViewById(R.id.coordinator)
navigationdrawer = findViewById(R.id.navigationview)
drawerLayout = findViewById(R.id.drawerlayout)
actionbar()
var toggle = ActionBarDrawerToggle(
this#dashact,
drawerLayout,
R.string.open,
R.string.close
)
toggle.syncState()
drawerLayout.addDrawerListener(toggle)
hideSystemBars()
navigtiontitle("home")
supportFragmentManager.beginTransaction()
.replace(R.id.frame, frag1())
.commit()
drawerLayout.closeDrawers()
navigationdrawer.setNavigationItemSelectedListener {
if (it.isChecked==true){
it.isCheckable=true
}else{
it.isCheckable=false
}
when (it.itemId) {
R.id.home -> {
navigtiontitle("home")
supportFragmentManager.beginTransaction()
.replace(R.id.frame, frag1())
.commit()
drawerLayout.closeDrawers()
}
R.id.fav ->{
navigtiontitle("Favourites")
supportFragmentManager.beginTransaction()
.replace(R.id.frame,Viewpager2())
.commit()
drawerLayout.closeDrawers()
}
R.id.privacy ->{
navigtiontitle("Privacy Policies")
supportFragmentManager.beginTransaction()
.replace(R.id.frame,privacy())
.commit()
drawerLayout.closeDrawers()
}
R.id.details ->{
navigtiontitle("My Details")
supportFragmentManager.beginTransaction()
.replace(R.id.frame,MyFrag())
.commit()
drawerLayout.closeDrawers()
}
}
return#setNavigationItemSelectedListener true
}
}
fun navigtiontitle(title: String) {
supportActionBar?.title = title
}
fun actionbar() {
super.setSupportActionBar(toolbar)
supportActionBar?.title = "Bookhub"
supportActionBar?.setHomeButtonEnabled(true)
supportActionBar?.setDisplayHomeAsUpEnabled(true)
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
when (item.itemId) {
android.R.id.home -> drawerLayout.openDrawer(GravityCompat.START)
}
return super.onOptionsItemSelected(item)
}
fun hideSystemBars() {
val windowInsetsController =
ViewCompat.getWindowInsetsController(window.decorView) ?: return
// Configure the behavior of the hidden system bars
windowInsetsController.systemBarsBehavior =
WindowInsetsControllerCompat.BEHAVIOR_SHOW_TRANSIENT_BARS_BY_SWIPE
// Hide both the status bar and the navigation bar
windowInsetsController.hide(WindowInsetsCompat.Type.systemBars())
}
}
xml of main activity:
<?xml version="1.0" encoding="utf-8"?>
<androidx.drawerlayout.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/drawerlayout"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
>
<androidx.coordinatorlayout.widget.CoordinatorLayout
android:id="#+id/coordinator"
android:layout_width="match_parent"
android:layout_height="match_parent">
<com.google.android.material.appbar.AppBarLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:theme="#style/ThemeOverlay.AppCompat.Dark"
android:elevation="0dp" >
<androidx.appcompat.widget.Toolbar
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:minHeight="?attr/actionBarSize"
/>
</com.google.android.material.appbar.AppBarLayout>
<FrameLayout
android:id="#+id/frame"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:layout_behavior="#string/appbar_scrolling_view_behavior" />
</androidx.coordinatorlayout.widget.CoordinatorLayout>
<com.google.android.material.navigation.NavigationView
android:id="#+id/navigationview"
android:layout_width="wrap_content"
android:layout_height="match_parent"
app:headerLayout="#layout/headers"
app:menu="#menu/icons"
android:layout_gravity="start"/>
</androidx.drawerlayout.widget.DrawerLayout>
themes.xml:
<resources xmlns:tools="http://schemas.android.com/tools">
<!-- Base application theme. -->
<style name="Test" parent="Theme.MaterialComponents.DayNight.NoActionBar">
<!-- Primary brand color. -->
<item name="colorPrimary">#color/purple_200</item> //for action bar
<item name="colorPrimaryVariant">#color/white</item> //can use to set status bar
<item name="colorOnPrimary">#color/purple_200</item>
<!-- Secondary brand color. -->
<item name="colorSecondary">#color/teal_200</item>
<item name="colorSecondaryVariant">#color/teal_700</item>
<item name="colorOnSecondary">#color/black</item>
<!-- Status bar color. -->
<item name="android:statusBarColor" tools:targetApi="l">#color/purple_200</item>
<!-- Customize your theme here. -->
</style>
<style name="splashs" parent="Theme.MaterialComponents.DayNight.NoActionBar">
<item name="android:windowBackground">#drawable/splash</item>
<item name="android:statusBarColor" tools:targetApi="l">#color/purple_200</item>
</style>
</resources>
You are hiding your system bars(status and navigation) in hideSystemBars() method. You are getting a black status bar probably due to a display cutout.
Find more about supporting display cutout here

setNavigationItemSelectedListener is not working

When i click the item in the navigation drawer it suppose to show toast message but it does not work. I've checked the other function shows the toast but only navigation drawer doesn't respond. Please help to find out why it is not working. Why toast message is not appearing.
class MainActivity : AppCompatActivity(){
lateinit var toolbar: Toolbar
lateinit var drawerLayout: DrawerLayout
lateinit var navView: NavigationView
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
toolbar = findViewById(R.id.toolbar)
setSupportActionBar(toolbar)
supportActionBar!!.setDisplayShowHomeEnabled(false)
supportActionBar!!.setDisplayHomeAsUpEnabled(false)
drawerLayout = findViewById(R.id.drawer_layout)
navView = findViewById(R.id.nav_view)
val toggle = ActionBarDrawerToggle(
this, drawerLayout, toolbar, 0, 0
)
drawerLayout.addDrawerListener(toggle)
navView.setNavigationItemSelectedListener(object :
NavigationView.OnNavigationItemSelectedListener{
override fun onNavigationItemSelected(item: MenuItem): Boolean {
when (item.itemId) {
R.id.nav1 -> {
toast("Update")
}
R.id.nav2 -> {
toast("Update")
}
R.id.nav3 -> {
toast("Update")
}
R.id.nav4 -> {
toast("Update")
}
R.id.nav5 -> {
toast("Update")
}
R.id.nav6 -> {
toast("Update")
}
R.id.nav7 -> {
toast("Update")
}
R.id.nav8 -> {
toast("Update")
}
R.id.nav9 -> {
toast("Update")
}
}
return true
}
})
bottomNavigationView.setOnNavigationItemSelectedListener { item: MenuItem ->
return#setOnNavigationItemSelectedListener when (item.itemId) {
R.id.main -> {
replaceFragment(GlavnayaFragment())
toast("Главная")
true
}
R.id.izbraniye -> {
replaceFragment(IzbraniyeFragment())
true
}
R.id.tickets -> {
replaceFragment(TicketsFragment())
true
}
R.id.cabinet -> {
replaceFragment(KabinetFragment())
true
}
R.id.basket -> {
replaceFragment(KarzinkiFragment())
true
}
else -> false
}
}
replaceFragment(GlavnayaFragment())
}
private fun replaceFragment(fragment: Fragment){
val fragmentTransaction = supportFragmentManager.beginTransaction()
fragmentTransaction.replace(R.id.drawer_layout,fragment)
fragmentTransaction.commit()
}
override fun onCreateOptionsMenu(menu: Menu?): Boolean {
menuInflater.inflate(R.menu.right_side_menu,menu)
return true
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
if(item!!.itemId == R.id.btnMyMenu){
if(drawerLayout.isDrawerOpen(Gravity.RIGHT)){
drawerLayout.closeDrawer(Gravity.RIGHT)
}
else{
drawerLayout.openDrawer(Gravity.RIGHT)
}
}
return super.onOptionsItemSelected(item)
}}
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.drawerlayout.widget.DrawerLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true"
tools:openDrawer="end">
<include
layout="#layout/content_main"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
<com.google.android.material.navigation.NavigationView
android:id="#+id/nav_view"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_gravity="end"
android:fitsSystemWindows="true"
app:headerLayout="#layout/nav_header"
app:menu="#menu/nav_menu"/>
</androidx.drawerlayout.widget.DrawerLayout>
nav_menu.xml
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
>
<group android:checkableBehavior="single">
<item
android:id="#+id/nav1"
android:title="Как это работает"/>
<item
android:id="#+id/nav2"
android:title="Продукты"/>
<item
android:id="#+id/nav3"
android:title="Благотворительная"/>
<item
android:id="#+id/nav4"
android:title="Компании"/>
<item
android:id="#+id/nav5"
android:title="Выбрать Язык"/>
</group>
<item android:title="Связаться c нами">
<menu>
<item
android:id="#+id/nav6"
android:title="Тел: 8800 7867896"
android:icon="#drawable/ic_phone"/>
<item
android:id="#+id/nav7"
android:title="e-mail: info#buywin.uz "
android:icon="#drawable/ic_email"/>
</menu>
</item>
<item android:title="Настройка учетной записи">
<menu>
<item
android:id="#+id/nav8"
android:title="Регистрация"
android:icon="#drawable/ic_registration"/>
<item
android:id="#+id/nav9"
android:title="Войти"
android:icon="#drawable/ic_in"/>
</menu>
</item>
</menu>
You should add setNavigationItemSelectedListener
Set a listener that will be notified when a menu item is selected.
navView.setNavigationItemSelectedListener(this)
Then
override fun onNavigationItemSelected(item: MenuItem): Boolean {
// Handle navigation view item clicks here.
when (item.itemId) {
R.id.nav1 -> {
toast("Update")
}
......
}
drawerLayout.closeDrawer(GravityCompat.START)
return true
}
FYI
You will override the method of its interface. NavigationView.OnNavigationItemSelectedListener
class MainActivity : AppCompatActivity(), NavigationView.OnNavigationItemSelectedListener{}

Navigation drawer menu item click no response

I am developing an android app and am new to programming. I have extended the base drawer activity to all activity. But after I clicked the menu button of the drawer in the activities that extend drawer activity, nothing happened. Below is my code in the base drawer activity.
open class DrawerActivity : AppCompatActivity(), NavigationView.OnNavigationItemSelectedListener {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
this.requestWindowFeature(Window.FEATURE_NO_TITLE)
this.window.setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN)
setContentView(R.layout.activity_drawer)
setSupportActionBar(toolbar)
nav_view.setNavigationItemSelectedListener(this)
pageToGo = 1
println("PageToGo on start activity: $pageToGo")
}
override fun onBackPressed() {
println("Back is pressed")
if (drawer_layout.isDrawerOpen(GravityCompat.END)) {
drawer_layout.closeDrawer(GravityCompat.END)
} else {
finishAffinity()
}
}
override fun onCreateOptionsMenu(menu: Menu): Boolean {
// Inflate the menu; this adds items to the action bar if it is present.
menuInflater.inflate(R.menu.drawer, menu)
return true
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
// 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.
when (item.itemId) {
R.id.action_settings -> return true
else -> return super.onOptionsItemSelected(item)
}
}
override fun onNavigationItemSelected(item: MenuItem): Boolean {
// Handle navigation view item clicks here.
when (item.itemId) {
R.id.nav_show_stat -> {
println("I am clicked")
}
R.id.nav_restart_game -> {
}
R.id.nav_achievements -> {
}
R.id.nav_settings -> {
}
R.id.nav_about_us -> {
}
R.id.nav_contact_us -> {
}
}
drawer_layout.closeDrawer(GravityCompat.END)
return true
}
override fun setContentView(layoutResID:Int) {
val fullLayout: DrawerLayout
val actContent: FrameLayout
fullLayout = layoutInflater.inflate(R.layout.activity_drawer, null) as DrawerLayout
actContent = fullLayout.findViewById(R.id.act_content) as FrameLayout
layoutInflater.inflate(layoutResID, actContent, true)
super.setContentView(fullLayout)
}
Below is my drawer_layout
<?xml version="1.0" encoding="utf-8"?>
<android.support.v4.widget.DrawerLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true"
tools:openDrawer="end">
<include
layout="#layout/app_bar_drawer"
android:layout_width="match_parent"
android:layout_height="match_parent" />
<FrameLayout
android:id="#+id/act_content"
android:layout_width="match_parent"
android:layout_height="match_parent">
</FrameLayout>
<android.support.design.widget.NavigationView
android:id="#+id/nav_view"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_gravity="end"
android:fitsSystemWindows="true"
app:headerLayout="#layout/nav_header_drawer"
app:menu="#menu/activity_drawer_drawer">
</android.support.design.widget.NavigationView>
Below is my menu code
<?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/nav_show_stat"
android:icon="#drawable/ic_menu_camera"
android:title="#string/nav_show_stat" />
<item
android:id="#+id/nav_restart_game"
android:icon="#drawable/ic_menu_gallery"
android:title="#string/nav_restart" />
<item
android:id="#+id/nav_achievements"
android:icon="#drawable/ic_menu_slideshow"
android:title="#string/nav_achievements" />
<item
android:id="#+id/nav_settings"
android:icon="#drawable/ic_menu_manage"
android:title="#string/nav_settings" />
</group>
<item android:title="#string/nav_our_company">
<menu>
<item
android:id="#+id/nav_about_us"
android:icon="#drawable/ic_menu_share"
android:title="#string/nav_about_us" />
<item
android:id="#+id/nav_contact_us"
android:icon="#drawable/ic_menu_send"
android:title="#string/nav_contact_us" />
</menu>
</item>
Below is my code in main activity
class MainActivity : DrawerActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
load()
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
beginAdventure()
main_layout.setOnTouchListener(object : OnSwipeTouchListener(applicationContext) {
override fun onSwipeLeft() {
drawer_layout.openDrawer(GravityCompat.END)
}
})
}
private fun beginAdventure() {
start_game_btn.setSafeOnClickListener {
nextPage("ChapterOneActOneActivity", 1)
}
}
}
I know I am missing something important. But I just don't know what it is. The onNavigationItemSelected seems not working because when I click on R.id.nav_show_stat, "I am clicked" never gets printed. Please kindly let me know what I should do to make the drawer buttons work in all activity. Thank you in advance.
Edit2: my drawer in main activity
https://imgur.com/a/ofGzncZ
So when I click on Show Statistics, the "I am clicked" is never printed. How do I handle the click event to do what I want?
No need to use the below given code separately :-
override fun setContentView(layoutResID:Int) {
val fullLayout: DrawerLayout
val actContent: FrameLayout
fullLayout = layoutInflater.inflate(R.layout.activity_drawer, null) as DrawerLayout
actContent = fullLayout.findViewById(R.id.act_content) as FrameLayout
layoutInflater.inflate(layoutResID, actContent, true)
super.setContentView(fullLayout)
}
just add :-
setContentView(R.layout.your_layout_filename);
i think there is no other issue in your code

How to avoid/overcome animations on bottom navigation bar on android

The navigation bar has 4 buttons, all of color gray. Each one inflates a specific fragment. when clicked on it,it changes its color to red.
The button which is clicked is also becoming larger(bigger).I want to change the color(gray to red) but not size.
How to achieve this (not changing the size of button)?
Thanks in advance.
The following is the part of the code:
Menu xml:
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">
<item
android:id="#+id/navigation_home"
android:icon="#drawable/ic_feed"
android:title=""/>
<item
android:id="#+id/navigation_dashboard"
android:icon="#drawable/ic_analytics"
android:title="" />
<item
android:id="#+id/navigation_profile"
android:icon="#drawable/ic_profile"
android:title="" />
<item
android:id="#+id/navigation_settings"
android:icon="#drawable/ic_settings"
android:title="" />
</menu>
kotlin code:
private lateinit var bottomnav : BottomNavigationView
val navUtils = NavigationUtils()
private val mOnNavigationItemSelectedListener =
BottomNavigationView.OnNavigationItemSelectedListener { item ->
when (item.itemId) {
R.id.navigation_home -> {
val locationhistoryinstance =
LocationHistoryFragment.newInstance()
loadFragment(locationhistoryinstance)
setTitle("Calender Test")
return#OnNavigationItemSelectedListener true
}
R.id.navigation_dashboard -> {
val analyticsinstance = AnalyticsPageFragment.newInstance()
loadFragment(analyticsinstance)
setTitle("Analytics")
return#OnNavigationItemSelectedListener true
}
R.id.navigation_profile -> {
val profileinstance = ProfileFragment.newInstance()
loadFragment(profileinstance)
setTitle("Profile")
return#OnNavigationItemSelectedListener true
}
R.id.navigation_settings -> {
val settingsinstance = SettingsFragment.newInstance()
loadFragment(settingsinstance)
setTitle("Settings")
return#OnNavigationItemSelectedListener true
}
}
false
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_home)
navigation.setOnNavigationItemSelectedListener(mOnNavigationItemSelectedListener)
bottomnav = findViewById(R.id.navigation)
navUtils.disableShiftMode(bottomnav)
}

TabLayout selected text color showing up in two tabs at the same time

I have tabLayout with ViewPager, but when I select a tab, previously selected tab text color will stay in selected color aswell. So I ended up with two tabs in selected text state. As you can see I made onTabSelectedListener to change icons from selected to unselected state and it's working fine. Only text is a problem. I've also tried to make xml selector for tabLayout before, but it did not work eventually.
UPDATE - When i removed tabLayout.addOnTabSelectedListener, text color is switching correctly. But this solved my problem only partialy. Now I have to find solution to icon swapping when Tab is selected.
tab.icon = getDrawable(iconListActive[viewPager.currentItem])
This exact code bugged out color switching. But it doesn't make sense. As I add super.onTabSelected(tab) color switching works perfectly.
TabLayout and ViewPager initialization:
private var pagerAdapter: ViewPagerAdapter? = null
private lateinit var viewPager: CustomViewPager
private lateinit var tabLayout: TabLayout
tabLayout = findViewById(R.id.tab_layout)
viewPager = findViewById(R.id.viewPager)
tabLayout.setTabTextColors(
resources.getColor(R.color.color_grey),
resources.getColor(R.color.color_green)
)
pagerAdapter = ViewPagerAdapter(supportFragmentManager, this)
pagerAdapter!!.apply {
addFragment(FirstFragment(), "Tab 1")
addFragment(SecondFragment(), "Tab 2")
addFragment(ThirdFragment(), "Tab 3")
addFragment(FourthFragment(), "Tab 4")
}
viewPager.adapter = pagerAdapter
tabLayout.setupWithViewPager(viewPager)
tabLayout.tabGravity = (TabLayout.GRAVITY_FILL)
tabLayout.addOnTabSelectedListener(object : TabLayout.ViewPagerOnTabSelectedListener(viewPager) {
override fun onTabSelected(tab: TabLayout.Tab) {
tab.icon = getDrawable(iconListActive[viewPager.currentItem])
}
override fun onTabUnselected(tab: TabLayout.Tab) {
tab.icon = getDrawable(iconList[viewPager.currentItem])
}
})
}
CustomViewPager
import android.content.Context
import android.support.v4.view.ViewPager
import android.util.AttributeSet
import android.view.MotionEvent
class CustomViewPager(context: Context, attributeSet: AttributeSet) : ViewPager(context, attributeSet) {
override fun onInterceptTouchEvent(ev: MotionEvent?): Boolean {
return false
}
override fun onTouchEvent(ev: MotionEvent?): Boolean {
return false
}
}
ViewPagerAdapter
class ViewPagerAdapter(fm: FragmentManager, private val ctx: Context) : FragmentStatePagerAdapter(fm) {
private val fragments = ArrayList<Fragment>()
private val tabTitles = ArrayList<String>()
override fun getItem(position: Int): Fragment {
return fragments[position]
}
override fun getCount(): Int {
return fragments.size
}
fun addFragment(fragment: Fragment, tabtitle: String){
fragments.add(fragment)
tabTitles.add(tabtitle)
}
override fun getPageTitle(position: Int): CharSequence {
return tabTitles[position]
}
TabLayout and ViewPager XML
<FrameLayout
android:id="#+id/frameContainer"
android:layout_width="0dp"
android:layout_height="0dp"
app:layout_constraintBottom_toTopOf="#+id/tab_layout"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent">
<com.app.CustomViewPager
android:id="#+id/viewPager"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#color/colorBackground" />
</FrameLayout>
<android.support.design.widget.TabLayout
android:id="#+id/tab_layout"
style="#style/TabBarTheme"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:elevation="4dp"
android:visibility="visible"
android:minHeight="?attr/actionBarSize"
android:layout_alignParentBottom="true"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent" />
TabStyle XML:
<style name="TabBarTheme" parent="Widget.Design.TabLayout">
<item name="android:background">#color/colorBackground</item>
<item name="tabTextAppearance">#style/AppTabTextAppearance</item>
<item name="tabIndicatorHeight">0dp</item>
</style>
<style name="AppTabTextAppearance" parent="TextAppearance.AppCompat.Widget.ActionBar.Title.Inverse">
<item name="textAllCaps">false</item>
<item name="android:capitalize">words</item>
<item name="android:textSize">10sp</item>
</style>
Graphical representation of that behaviour (cannot post actual graphics)
Use the following style code to change the color of the text in TabLayout on selection.
<style name="MyCustomTabLayout" parent="Widget.Design.TabLayout">
<item name="tabIndicatorColor">#color/colorPrimary</item>
<item name="tabTextAppearance">#style/MyCustomTabText</item>
<item name="tabSelectedTextColor">#color/colorPrimary</item>
</style>
<style name="MyCustomTabText" parent="TextAppearance.AppCompat.Button">
<item name="android:textSize">14sp</item>
<item name="android:textColor">#android:color/black</item>
<item name="android:textAllCaps">false</item>
</style>
And use this style in your TabLayout.
<android.support.design.widget.TabLayout
android:id="#+id/tab_layout"
style="#style/MyCustomTabLayout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:elevation="4dp"
android:visibility="visible"
android:minHeight="?attr/actionBarSize"
android:layout_alignParentBottom="true"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent" />
You need use CustomView for Tablayout and set selector false for tab CustomView at onTabUnselected.
Like below:
View view = tab.getCustomView();
if (view != null) {
tab.icon = getDrawable(iconList[viewPager.currentItem])
view.setSelected(false);
}

Categories

Resources