I have prepared the custom toolbar toolbar.xml file as below:
<?xml version="1.0" encoding="utf-8"?>
<androidx.appcompat.widget.Toolbar xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
xmlns:layout="http://schemas.android.com/tools"
android:id="#+id/my_toolbar1"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:background="#BCBCDD"
android:elevation="4dp"
app:logo="#drawable/ic_baseline_menu_24"
android:theme="#style/ThemeOverlay.AppCompat.Dark.ActionBar">
</androidx.appcompat.widget.Toolbar>
Now I have created a menu directory, and in that toolbar_menu.xml file as below:
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">
<item
android:id="#+id/menu_share"
android:title="Share"/>
<item
android:id="#+id/menu_settings"
app:showAsAction="always"
android:icon="#drawable/ic_baseline_settings_24"
android:title="Settings"/>
<item
android:id="#+id/menu_exit"
android:title="Exit"/>
</menu>
Now I have included this toolbar layout in my main activity. xml with <include/> tag.
After all this implementation I have set the toolbar in MainActivity.kt which is as below:
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
setSupportActionBar(my_toolbar.findViewById(R.id.my_toolbar1)) //Set the Action Bar -> toolbar
val apiService : ApiService = ApiClient.getClient()
coronaRepository =
CoronaDetailsRepository(
apiService
)
viewModel = getViewModel(1,1)
viewModel.coronaDetails.observe(this, Observer {
bindUI(it)
})
viewModel.networkState.observe(this, Observer {
loader.visibility = if (it == NetworkState.LOADING) View.VISIBLE else View.GONE
})
}
override fun onCreateOptionsMenu(menu: Menu?): Boolean {
menuInflater.inflate(R.menu.toolbar_menu, menu) // Used Menu Inflater to inflate the layout
return true
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
when(item.itemId){
R.id.menu_share -> Toast.makeText(applicationContext, "Share", Toast.LENGTH_SHORT).show()
R.id.menu_settings -> Toast.makeText(applicationContext, "Settings", Toast.LENGTH_SHORT).show()
R.id.menu_exit -> Toast.makeText(applicationContext, "Exit", Toast.LENGTH_SHORT).show()
}
return super.onOptionsItemSelected(item)
}
My toolbar is appearing on the main screen when app runs but the menu is not visible. I am wondering that what is wrong going on in my code??
Inside onCreate
..
setSupportActionBar(findViewById(R.id.my_toolbar1))
..
Inside onCreateOptionsMenu
override fun onCreateOptionsMenu(menu: Menu): Boolean {
menuInflater.inflate(R.menu.menu_toolbar, menu)
return super.onCreateOptionsMenu(menu)
}
Related
I recently working on activating SearchView in ActionMode when user click on Search in onOptionsItemSelected.
However, I cant get access to the SearchView as after debugging, its actionView apparently to be null. Can anyone help me with this?
override fun onOptionsItemSelected(item: MenuItem): Boolean {
R.id.chat_search -> {
if (searchActionMode == null) {
searchActionMode = startActionMode(searchActionModeCallBack)
}
}
ActionModeCallBack
private val searchActionModeCallBack = object: ActionMode.Callback {
private lateinit var mSearchView: SearchView
override fun onCreateActionMode(mode: ActionMode?, menu: Menu?): Boolean {
menuInflater.inflate(R.menu.menu_search_message, menu)
moreMenuBtn.isVisible = false
layout_chatbox.hide()
return true
}
override fun onPrepareActionMode(mode: ActionMode?, menu: Menu?): Boolean {
val searchItem = menu?.findItem(R.id.search_item_btn)
if(searchItem?.actionView != null) { <---- this seachview.actionView keeps return null
mSearchView = searchItem.actionView as SearchView
mSearchView.isIconified = false
mSearchView.onQueryTextChanged { newText ->
}
}
return true
}
override fun onActionItemClicked(mode: ActionMode?, item: MenuItem?): Boolean {
when(item?.itemId) {
R.id.search_item_up -> {
"UP".showToast(this#ChatActivity)
}
R.id.search_item_down -> {
"DOWN".showToast(this#ChatActivity)
}
R.id.search_item_btn -> {
"SEARCH".showToast(this#ChatActivity) <-- when click on "Search" Button, "Search" is toasted.
}
}
return false
}
override fun onDestroyActionMode(mode: ActionMode?) {
searchActionMode = null
moreMenuBtn.isVisible = true
layout_chatbox.show()
}
}
menu_search_message.xml
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">
<group android:id="#+id/group_search_mode">
<item
android:id="#+id/search_item_btn"
android:icon="#drawable/ic_baseline_search_24"
app:showAsAction="always"
android:title="#string/search"
app:actionViewClass="androidx.appcompat.widget.SearchView" />
<item
android:id="#+id/search_item_up"
android:icon="#drawable/ic_baseline_arrow_drop_up_24"
app:showAsAction="always"
android:title="#string/up"/>
<item
android:id="#+id/search_item_down"
android:icon="#drawable/ic_baseline_arrow_drop_down_24"
app:showAsAction="always"
android:title="#string/down"/>
</group>
</menu>
I used androidx.appcompat.widget.SearchView for all of the SearchView I used. But still I had no idea why I can't access to the SearchView in ActionMode. Please give me some help.
I faced the same issue before, and what worked for me is to set the ActionView programmatically, not in menu xml.
To do that:
First: Remove the Action ViewClass from your menu
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">
<group android:id="#+id/group_search_mode">
<item
android:id="#+id/search_item_btn"
android:icon="#drawable/ic_baseline_search_24"
app:showAsAction="always"
android:title="#string/search"/>
...
Second: Create an instance of a SearchView
Third: Inflate the menu item that you want to set its actionViewClass, and use setActionView(view) to set your instantiated SearchView.
override fun onCreateActionMode(mode: ActionMode?, menu: Menu?): Boolean {
menuInflater.inflate(R.menu.menu_search_message, menu)
moreMenuBtn.isVisible = false
layout_chatbox.hide()
// Step 2:
val searchView = SearchView(this)
searchView.setQuery(null, true)
searchView.queryHint = "Search"
// Step 3:
val searchItem = menu?.findItem(R.id.search_item_btn)
searchItem.setActionView(searchView)
return true
}
I had a workaround for this.
In my case, I will add a customview to the actionMode's title.
Here is my solution.
override fun onOptionsItemSelected(item: MenuItem): Boolean {
R.id.chat_search -> {
if (searchActionMode == null) {
searchActionMode = startActionMode(searchActionModeCallBack)
val view = layoutInflater.inflate(R.layout.custom_searchview, null)
searchActionMode?.customView = view <-- ADD YOUR CUSTOM VIEW
val etSearch = view.findViewById<EditText>(R.id.et_search)
etSearch.requestFocus()
etSearch.doOnTextChanged { text, start, before, count ->
// TODO - handle the search query here
}
}
}
custom_searchview.xml (Just a simple EditText)
<RelativeLayout
android:layout_height="match_parent"
android:layout_width="match_parent"
xmlns:android="http://schemas.android.com/apk/res/android" >
<EditText
android:id="#+id/et_search"
android:layout_alignParentStart="true"
android:maxLines="1"
android:ellipsize="end"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#null"
android:padding="10dp"
android:layout_marginEnd="50dp"
android:hint="Search..."
android:textColorHint="#color/colorWhite"
android:textColor="#color/colorWhite"/>
</RelativeLayout>
menu_search_message.xml (REMOVE THE SEARCH VIEW ITEM)
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">
<!-- <item--> <-- remove the searchView from xml
<!-- android:id="#+id/search_item_btn"-->
<!-- android:icon="#drawable/ic_baseline_search_24"-->
<!-- android:title="#string/search"-->
<!-- android:enabled="true"-->
<!-- android:actionLayout="#layout/custom_searchview"-->
<!-- app:showAsAction="collapseActionView|always" />-->
<item
android:id="#+id/search_item_up"
android:icon="#drawable/ic_baseline_arrow_drop_up_24"
android:orderInCategory="2"
android:title="#string/up"
app:showAsAction="always" />
<item
android:id="#+id/search_item_down"
android:icon="#drawable/ic_baseline_arrow_drop_down_24"
android:orderInCategory="3"
android:title="#string/down"
app:showAsAction="always" />
</menu>
Final output will be like this
Icons in the option menu work just fine, but when you change orientation by rotating the screen the icons disappear.
class SingleRecipeFragment : Fragment() {
private lateinit var viewModel: SingleRecipeViewModel
private lateinit var viewModelFactory: SingleRecipeViewModelFactory
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
val binding: FragmentSingleRecipeBinding = DataBindingUtil.inflate(inflater,
R.layout.fragment_single_recipe, container, false)
val args =
SingleRecipeFragmentArgs.fromBundle(
requireArguments()
)
val application = requireNotNull(this.activity).application
viewModelFactory =
SingleRecipeViewModelFactory(
args.recipeIndex, application
)
viewModel = ViewModelProvider(this,viewModelFactory)
.get(SingleRecipeViewModel::class.java)
binding.singleRecipeViewModel = viewModel
binding.lifecycleOwner = this
viewModel.curRecipe.observe(viewLifecycleOwner, Observer {
(requireActivity() as MainActivity).toolbar.title = it?.title
})
//Toast.makeText(context, "Recipe Number: ${args.recipeIndex}",Toast.LENGTH_LONG).show()
setHasOptionsMenu(true)
return binding.root
}
override fun onCreateOptionsMenu(menu: Menu, inflater: MenuInflater) {
super.onCreateOptionsMenu(menu, inflater)
inflater.inflate(R.menu.single_recipe_menu, menu)
viewModel.curRecipe.observe(viewLifecycleOwner, Observer {
val favIconDrawable: Int = if (it!!.favorite) R.drawable.ic_baseline_star_filled_24
else R.drawable.ic_baseline_star_border_24
menu.findItem(R.id.favorite).setIcon(favIconDrawable)
})
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
when (item.itemId) {
R.id.share -> viewModel.shareSuccess(this.requireActivity())
R.id.favorite -> viewModel.toggleFavorite()
}
return super.onOptionsItemSelected(item)
}
}
Here's the menu layout:
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">
<item
android:id="#+id/share"
android:enabled="true"
android:icon="#drawable/ic_baseline_share_24"
android:title="Share"
android:visible="true"
app:showAsAction="ifRoom" />
<item
android:id="#+id/favorite"
android:enabled="true"
android:icon="#drawable/ic_baseline_star_border_24"
android:title="Share"
android:visible="true"
app:showAsAction="ifRoom" />
</menu>
This fragment is launched from another fragment by NavigationUI which passes in the recipeID value. I've tried using setHasOptionsMenu(true) in the onResume of this fragment but it has no effect. Any idea why the optionsMenu is not persistent?
It seems that using setSupportActionBar(toolbar) in the onCreate() method of the MainActivity fixes the problem with the optionsMenu not being persistent. However, this breaks the method I was using to display the title on fragment windows.
The toolbar belongs to the Activity, not the fragment. So when the view is recreated after the orientation change the toolbar is being set to the app title. This doesn't happen when the fragment is first loaded since the title was being set by the fragment's onCreate(). So the solution to that was to move the custom titles to onResume() of the fragment so that it is reset ever time the view is shown on the screen.
I'm setting the title in the fragment like this, because if I let the Navigation Controller do it using the labels in navigation.xml I get a strange behavior when the fragment loads up where the custom toolbar layout being replace by the new fragment title kind of flashes out to the right.
So the boiled-down code for this solution is:
Fragment:
class SingleRecipeFragment : Fragment() {
override fun onCreateView(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setHasOptionsMenu(true)
}
override fun onResume() {
super.onResume()
/** This will reset your title every time the fragment is redrawn **/
(requireActivity() as MainActivity).toolbar.title = "Some Custom Title"
}
override fun onCreateOptionsMenu(menu: Menu, inflater: MenuInflater) {
super.onCreateOptionsMenu(menu, inflater)
inflater.inflate(R.menu.single_recipe_menu, menu)
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
when (item.itemId) {
R.id.share -> someMethodYouWantToRun()
R.id.favorite -> someOtherMethod()
}
return super.onOptionsItemSelected(item)
}
}
In onCreate() of your Activity, call:
setSupportActionBar(toolbar)
And here's the menu layout resource file being inflated for the options menu (no change from what's in the question):
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">
<item
android:id="#+id/share"
android:enabled="true"
android:icon="#drawable/ic_baseline_share_24"
android:title="Share"
android:visible="true"
app:showAsAction="ifRoom" />
<item
android:id="#+id/favorite"
android:enabled="true"
android:icon="#drawable/ic_baseline_star_border_24"
android:title="Share"
android:visible="true"
app:showAsAction="ifRoom" />
</menu>
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{}
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
Question: How to make the search menu item focused when activity start?
I would like the activity started as 2nd image as below.
Here with my code:
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_search_qpon)
setSupportActionBar(qponSearch_toolbar)
}
override fun onCreateOptionsMenu(menu: Menu): Boolean {
// Inflate the menu to use in the action bar
menuInflater.inflate(R.menu.search_menu, menu)
val searchItem = menu.findItem(R.id.app_bar_search)
if (searchItem!=null) {
val searchView = searchItem.actionView as SearchView
val searchHint = getString(R.string.searchHint)
searchView.setQueryHint(searchHint)
searchView.setOnQueryTextListener(object : SearchView.OnQueryTextListener {
override fun onQueryTextSubmit(query: String?): Boolean {
return false
}
override fun onQueryTextChange(newText: String?): Boolean {
if (newText!!.toString().isNotEmpty()) {
startRecyclerView(generateData(newText))
companyList.clear()
}
else {
startRecyclerView(generateData(newText))
companyList.clear()
}
return false
}
})
}
return super.onCreateOptionsMenu(menu)
}
Here with the xml file:
<?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"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#mipmap/bg"
android:orientation="vertical"
tools:context=".SearchQponActivity">
<android.support.v7.widget.Toolbar
android:id="#+id/qponSearch_toolbar"
android:layout_width="match_parent"
app:title=""
android:layout_height="56dp"
android:background="#color/white50"
android:elevation="4dp"
android:theme="#style/ThemeOverlay.AppCompat.ActionBar"
app:popupTheme="#style/ThemeOverlay.AppCompat.Light"
/>
<android.support.v7.widget.RecyclerView
android:id="#+id/qponSearch_recyclerView"
android:layout_width="match_parent"
android:layout_height="wrap_content" >
</android.support.v7.widget.RecyclerView>
</LinearLayout>
Here with the MENU file:
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
>
<item
android:id="#+id/app_bar_search"
android:icon="#android:drawable/ic_menu_search"
android:title="Search"
app:actionViewClass="android.support.v7.widget.SearchView"
app:showAsAction="always" />
</menu>
1st image, this is what it shows now when the activity started:
2nd image, then I click the search button, it shows:
You have to call expandActionView() method of searchItem within onCreateOptionsMenu() method. Check the code given below:
override fun onCreateOptionsMenu(menu: Menu?): Boolean {
menuInflater.inflate(R.menu.test_menu, menu)
val searchItem = menu?.findItem(R.id.app_bar_search)
searchItem?.expandActionView() // This line will expand the search view.
....
}
Also, you have to make a change in your menu layout XML file. You have to change the property of showAsAction from always to ifRoom|collapseActionView. Check the code given below.
<item
android:id="#+id/app_bar_search"
android:icon="#android:drawable/ic_menu_search"
android:title="Search"
app:actionViewClass="android.support.v7.widget.SearchView"
app:showAsAction="ifRoom|collapseActionView" />