I use Android Studio with Kotlin and I have a problem with my Toolbar, when I create it, it hides my others elements on my activity =>
Without Toolbar
MainActivity.kt
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main))
val user = User("Bob", 20)
findViewById<Button>(R.id.go_to_second).setOnClickListener {
println("Lancement de la seconde activité")
val intent = Intent(this, Second::class.java)
intent.putExtra("user", user)
startActivity(intent)
}
findViewById<Button>(R.id.bouton_dialogue).setOnClickListener {
val confdial = ConfirmDialog()
confdial.listener = object: ConfirmDialog.ConfDeleteListener {
override fun onPositiveClick() {
Log.i("MainActivity", "Recuperation du postive suppression dialog")
val dd = FileListDialog()
dd.show(supportFragmentManager, "onPositiveClick")
}
override fun onNegativeClick() {
Log.i("MainActivity", "Confirmation du negative suppression dialog")
}
}
confdial.show(supportFragmentManager, "confirmDelete")
}
}
}
activity_main.xml :
<?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"
tools:context=".MainActivity">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!"
android:layout_gravity="center"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent"
android:visibility="visible"/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/go_to_second"
android:visibility="visible"
android:layout_gravity="center"
android:text="go pr l'aventure" />
<Button
android:id="#+id/bouton_dialogue"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:visibility="visible"
android:text="lancement dialogue" />
Result =>
result without toolbar
With Toolbar
MainActivity.kt
import android.content.Intent
import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import android.support.v7.widget.Toolbar
import android.util.Log
import android.view.Menu
import android.view.MenuItem
import android.widget.Button
import android.widget.Toast
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
val toolbar = findViewById<Toolbar>(R.id.toolbar)
setSupportActionBar(toolbar)
val user = User("Bob", 20)
findViewById<Button>(R.id.go_to_second).setOnClickListener {
println("Lancement de la seconde activité")
val intent = Intent(this, Second::class.java)
intent.putExtra("user", user)
startActivity(intent)
}
findViewById<Button>(R.id.bouton_dialogue).setOnClickListener {
val confdial = ConfirmDialog()
confdial.listener = object: ConfirmDialog.ConfDeleteListener {
override fun onPositiveClick() {
Log.i("MainActivity", "Recuperation du postive suppression dialog")
val dd = FileListDialog()
dd.show(supportFragmentManager, "onPositiveClick")
}
override fun onNegativeClick() {
Log.i("MainActivity", "Confirmation du negative suppression dialog")
}
}
confdial.show(supportFragmentManager, "confirmDelete")
}
}
override fun onCreateOptionsMenu(menu: Menu?): Boolean {
menuInflater.inflate(R.menu.main_menu, menu)
return true
}
override fun onOptionsItemSelected(item: MenuItem?): Boolean {
when(item?.itemId){
R.id.action_second -> {
val intent = Intent(this, Menu_activiy::class.java)
startActivity(intent)
return true
}
R.id.action_delete -> {
Toast.makeText(this, "supprimer", Toast.LENGTH_LONG).show()
return true
}
else -> return super.onOptionsItemSelected(item)
}
}
}
activity_main.xml
<?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"
tools:context=".MainActivity">
<android.support.v7.widget.Toolbar
android:id="#+id/toolbar"
android:layout_height="?attr/actionBarSize"
android:layout_width="match_parent"
android:background="#color/colorPrimary"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!"
android:layout_gravity="center"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent"
android:visibility="visible"/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/go_to_second"
android:visibility="visible"
android:layout_gravity="center"
android:text="go pr l'aventure" />
<Button
android:id="#+id/bouton_dialogue"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:visibility="visible"
android:text="lancement dialogue" />
</LinearLayout>
main_menu.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">
<item android:id="#+id/action_second"
android:icon="#mipmap/ic_launcher_round"
android:title="Seconde"
app:showAsAction="always"/>
<item android:id="#+id/action_save"
android:icon="#drawable/epee"
android:title="Enregistrer"
app:showAsAction="always"/>
<item android:id="#+id/action_delete"
android:icon="#drawable/pioche"
android:title="Supprimer"
app:showAsAction="ifRoom"/>
<item android:id="#+id/action_help"
android:icon="#drawable/pomme"
android:title="Aide"
app:showAsAction="never"/>
</menu>
Result with ToolBar =>
Result with ToolBar
So we can see ToolBar but others elements like "Hello World" TextView has disappeared
Set the orientation of the LinearLayout:
android:orientation="horizontal" or android:orientation="vertical" also delete all the attributes that refer to ConstraintLayout.
Your toolbar's width is match_parent. This mean toolbar width is same your parent view. Your other views are still there but they are not visible, because LinearLayout's orientation is horizontal. They are out of parent view (LinearLayout).
You must change your parent layouts orientation to vertical or change your parent views type.
I guess the problem is the same which is stated in the above answer.
When the orientation of a LinearLayout is unspecified, it is using the default, which is horizontal. Should the layout be a column or a row? Use "horizontal" for a row, "vertical" for a column. The default is horizontal.
Since you are not giving any orientation it's horizontal and pushing other views out of scope so you better give a orientation in your linear layout.
android:orientation="vertical"
you can margin your hello world textView with
android:layout_marginTop="?attr/actionBarSize"
Related
I have a block of text that extends past both the display width and height. I want to scroll both vertically and horizontally. I am using a TextView and set both scrollbars. I also tried extending the size of the TextView past the parent. This correctly displays the String as I was hoping except the view does not scroll.
I have a simple app with two tabs. I change the text report based on tab selection which is very simple. I would like to make this work before complicating the code with fragments and pageviews
This is my main_activity.xml file...
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout 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"
tools:context=".MainActivity">
<com.google.android.material.tabs.TabLayout
android:id="#+id/tabs"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:layout_constraintTop_toTopOf="parent"
app:tabGravity="fill"
app:tabMode="fixed" />
<TextView
android:id="#+id/report_view"
android:layout_width="1000dp"
android:layout_height="1000dp"
android:lineSpacingExtra="1sp"
android:scrollbars="horizontal|vertical"
android:typeface="monospace"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/tabs" />
</androidx.constraintlayout.widget.ConstraintLayout>
And this is my MainActivity.kt file...
package com.example.tabtest
import android.os.Bundle
import android.widget.TextView
import androidx.appcompat.app.AppCompatActivity
import com.google.android.material.tabs.TabLayout
import com.google.android.material.tabs.TabLayout.OnTabSelectedListener
class MainActivity : AppCompatActivity()
{
override fun onCreate(savedInstanceState: Bundle?)
{
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
val tabLayout: TabLayout = findViewById(R.id.tabs)
tabLayout.addTab(tabLayout.newTab().setText("Report 1"))
tabLayout.addTab(tabLayout.newTab().setText("Report 2"))
// report 1
var report1 = "Report 1"
for (index in 1..5)
{
report1 = "$report1\nline $index"
}
report1 = "$report1\nvery long line like this one: ################################################ "
// report 2
var report2 = "Monthly Report"
for (index in 1..25)
{
report2 = "$report2\nline $index"
}
val view: TextView = findViewById(R.id.report_view)
view.text = report1
tabLayout.addOnTabSelectedListener(object : OnTabSelectedListener
{
override fun onTabSelected(tab: TabLayout.Tab)
{
if (tabLayout.selectedTabPosition == 0)
{
view.text = report1
} else if (tabLayout.selectedTabPosition == 1)
{
view.text = report2
}
}
override fun onTabUnselected(tab: TabLayout.Tab)
{
}
override fun onTabReselected(tab: TabLayout.Tab)
{
}
})
}
}
This is my output...
Report 1 tab
Report 2 tab
I try to combine drawer layout with viewapger2 and Navhostfragment. When I clicked the drawer layout icon, NavigationView (that include my menu and header) is opened. whenever ı try to select one item from drawer layout , ı cant select because drawer layout is automatically close. How can ı fix this problem.
this is my activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<layout>
<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"
tools:context=".MainActivity">
<com.google.android.material.navigation.NavigationView
android:id="#+id/navView"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_gravity="start"
android:fitsSystemWindows="true"
app:headerLayout="#layout/nav_header"
app:menu="#menu/nav_menu" />
<androidx.fragment.app.FragmentContainerView
android:id="#+id/fragmentContainerView"
android:name="androidx.navigation.fragment.NavHostFragment"
android:layout_width="0dp"
android:layout_height="0dp"
android:layout_marginStart="1dp"
android:layout_marginTop="1dp"
android:layout_marginEnd="1dp"
android:layout_marginBottom="1dp"
app:defaultNavHost="true"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:navGraph="#navigation/my_nav" />
</androidx.drawerlayout.widget.DrawerLayout>
</layout>
fragment_view_pager.xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
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="#drawable/beach4"
android:id="#+id/cons"
tools:context=".view.ViewPagerFragment">
<androidx.viewpager2.widget.ViewPager2
android:id="#+id/view_pager"
android:layout_width="0dp"
android:layout_height="0dp"
android:layout_marginTop="75dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<com.google.android.material.tabs.TabLayout
android:id="#+id/tab_layout"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_gravity="top"
android:background="#00ffffff"
android:layout_marginTop="40dp"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="#+id/cons"
app:tabBackground="#drawable/tab_pager_selector"
app:tabGravity="center"
app:tabIndicatorHeight="0dp"
app:tabPaddingEnd="#dimen/tab_padding_end"
app:tabPaddingStart="#dimen/tab_padding_start"
tools:ignore="MissingConstraints" />
</androidx.constraintlayout.widget.ConstraintLayout>
NavHeader.xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
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="150dp"
android:background="#B3F6FF">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Mustafa"
android:textSize="25sp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>
nav_menu
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">
<item
android:id="#+id/firstItem"
android:title="First Item"/>
<item
android:id="#+id/secondItem"
android:title="Second Item"/>
<item
android:id="#+id/thirdItem"
android:title="Third Item"/>
MainActivity.kt
class MainActivity : AppCompatActivity() {
companion object {
var globalList = ArrayList<Float>()
var globalVar3=1
var globalVar = 1
var globalVar2 = 1
lateinit var sharedPreferences: SharedPreferences
lateinit var toggle: ActionBarDrawerToggle
lateinit var navVieww: NavigationView
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
sharedPreferences =
this.getSharedPreferences("com.mustafa.horizontalrecycler", Context.MODE_PRIVATE)
toggle = ActionBarDrawerToggle(
this#MainActivity,
drawer_layout,
R.string.Open,
R.string.Close
)
drawer_layout.addDrawerListener(toggle)
toggle.syncState()
supportActionBar?.setDisplayHomeAsUpEnabled(true)
val navView = findViewById<NavigationView>(R.id.navView)
navVieww = navView
navView.setNavigationItemSelectedListener {
when (it.itemId) {
R.id.firstItem -> {
Toast.makeText(applicationContext, "First Item Selected", Toast.LENGTH_LONG)
.show()
println("First Item")
}
R.id.secondItem -> {
Toast.makeText(applicationContext, "Second Item Selected", Toast.LENGTH_LONG)
.show()
println("Second Item")
}
R.id.thirdItem -> {
Toast.makeText(applicationContext, "Third Item Selected", Toast.LENGTH_LONG)
.show()
}
}
true
}
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
if (toggle.onOptionsItemSelected(item)) {
globalVar3= globalVar3+1
return true
}
return super.onOptionsItemSelected(item)
}
}
viewPagerFragment.kt
class ViewPagerFragment : Fragment() {
private val args by navArgs<ViewPagerFragmentArgs>()
private lateinit var wordViewModel: WordViewModel
var number = 1
private lateinit var tabLayout: TabLayout
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
println("VieewPagerOncreated")
}
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
// Inflate the layout for this fragment
val view = inflater.inflate(R.layout.fragment_view_pager, container, false)
wordViewModel = ViewModelProvider(this).get(WordViewModel::class.java)
wordViewModel.readAllData.observe(viewLifecycleOwner, Observer {
//println(it.size)
})
number = sharedPreferences.getInt("pageNumber", 1)
println(number)
val tabLayout = view.findViewById<TabLayout>(R.id.tab_layout)
val viewPager = view.findViewById<ViewPager2>(R.id.view_pager)
val fragments1: ArrayList<Fragment> = arrayListOf(
WeatherListFragment(),
Location1Fragment(),
Location2Fragment(),
Location3Fragment()
)
val fragments2: ArrayList<Fragment> = arrayListOf(
LocationAddFragment()
)
//(i in number..x) x sayısı locationfragment sayısından bir az olcak
//suan için istediğimiz gibi oldu
for (i in number..2) {
fragments1.removeLast()
}
//fragments1.add(fragments2.get(0))
val adapter =
ViewPagerAdapter(fragments1, requireActivity().supportFragmentManager, lifecycle)
viewPager.adapter = adapter
if (MainActivity.globalVar > 1) {
viewPager.setCurrentItem(args.currentPage, false)
}
TabLayoutMediator(tabLayout, viewPager)
{ tab, position -> }.attach()
// bu kod ile başlıgın ismini değiştirebiliriz
(activity as AppCompatActivity).supportActionBar?.title = "Ingredient Display"
(activity as AppCompatActivity).supportActionBar?.setDisplayHomeAsUpEnabled(true)
(activity as AppCompatActivity).navView.setNavigationItemSelectedListener {
when (it.itemId) {
R.id.firstItem -> {
println("viewpagerfragment")
Toast.makeText(requireContext(), "First Item Selected", Toast.LENGTH_LONG)
.show()
println("First Item")
}
R.id.secondItem -> {
Toast.makeText(requireContext(), "Second Item Selected", Toast.LENGTH_LONG)
.show()
println("Second Item")
}
R.id.thirdItem -> {
Toast.makeText(requireContext(), "Third Item Selected", Toast.LENGTH_LONG)
.show()
}
}
true
}
return view
}
}
i already define this :
class ProfileFragment : Fragment(), View.OnClickListener {}
and the onclick :
override fun onClick(v: View?) {
when (v!!.id) {
binding.tvNavSetting -> {
avoidDoubleClicks(binding.tvNavSetting)
val intent = Intent(requireContext(), SettingsActivity::class.java)
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP or Intent.FLAG_ACTIVITY_NEW_TASK)
startActivity(intent)
}
}
}
this is my Drawer & inside Profile Fragment.xml :
<com.google.android.material.navigation.NavigationView
app:elevation="10dp"
android:id="#+id/nav_view"
android:paddingBottom="100dp"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_gravity="end"
android:background="#color/white"
android:fitsSystemWindows="false">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<androidx.appcompat.widget.SearchView
android:layout_width="match_parent"
android:layout_height="40dp"
android:id="#+id/seach_view"
android:background="#drawable/bg_search"
android:layout_marginHorizontal="10dp"
android:layout_marginVertical="10dp"/>
// this is what i try to call:////
<TextView
android:id="#+id/tv_nav_setting"
android:text="awdadw"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textColor="#color/black" />
<View
android:layout_width="match_parent"
android:layout_height="1dp"
android:layout_marginStart="20dp"
android:layout_marginEnd="40dp"
android:background="#drawable/drawer_bg" />
</LinearLayout>
<Button
android:id="#+id/btn_keluar_profile"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Keluar"
android:layout_margin="10dp"
android:textColor="#color/white"
android:background="#drawable/bg_btn_login"
android:layout_gravity="bottom"/>
</com.google.android.material.navigation.NavigationView>
i have Text View inside the Drawer Navigation inside Fragment.. i want handle click in that drawer navigation, but the text view can't call by viewBinding.. please have a look the error picture below..
when(v!!.id) means you want to use view with particular id (works like old Java switch case or just if(view.id == id), so binding.tvNavSetting -> ... should be binding.tvNavSetting.id -> .... currently you are comparing views id with whole view-object itself
sorry , i forgot to add this :
override fun onClick(v: View?) {
when (v!!.id) {
R.id.tv_nav_setting -> { <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
avoidDoubleClicks(binding.tvNavSetting)
val intent = Intent(requireContext(), SettingsActivity::class.java)
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP or Intent.FLAG_ACTIVITY_NEW_TASK)
startActivity(intent)
}
}
}
/*adding this line solve the problem*/
private fun setDrawer() {
binding.drawerLayout.setScrimColor(Color.TRANSPARENT)
binding.tvNavSetting.setOnClickListener(this) <<<-------
}
Instead of using view ids in when(v!!.id), we can use the comparison of views.
i.e Bind Listenser first
binding.bt1.setOnClickListener(this)
binding.bt2.setOnClickListener(this)
binding.bt3.setOnClickListener(this)
binding.bt4.setOnClickListener(this)
then
override fun onClick(view: View?) {
binding.apply {
when(view) {
bt1 -> {
println("bt1")
}
bt2 -> {
println("bt2")
}
bt3 -> {
println("bt3")
}
bt4 -> {
println("bt4")
}
}
}
}
Works perfectly since binding.bt1 gives View only.
I want to create a Bottom Navigation Bar. I used android BottomNavigationView to create the UI but I don't know how to add an OnClick listener to the items in Menu.
I searched on google and found some articles, but all of them were using a Toolbar element. I don't know about how to add that and what it was doing.
This is my Navigation bar code which I am including in the main activity
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:design="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent">
<RelativeLayout android:layout_width="match_parent" android:id="#+id/bottom_nav"
android:background="#drawable/gradient_theme"
android:layout_height="wrap_content" android:layout_gravity="bottom">
<android.support.design.widget.BottomNavigationView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#android:color/white"
android:id="#+id/menuBar"
design:menu="#menu/menu_bar"
design:itemIconTint="#android:color/darker_gray"/>
</RelativeLayout>
</FrameLayout>
This is my MainActivity.kt in which i want to set Listeners
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
beautifyLayout(this, window)
setSupportActionBar(toolbar)
testButton.setOnClickListener {
val intent= Intent(this,AccountActivity::class.java)
finish()
startActivity(intent)
}
}
}
This is menu_bar.xml
<menu xmlns:android="http://schemas.android.com/apk/res/android" >
<item android:id="#+id/btn1" android:title="" android:icon="#drawable/ic_feed"/>
<item android:id="#+id/btn2" android:title="" android:icon="#drawable/ic_chat_bubble_black_24dp"/>
<item android:id="#+id/btn3" android:title="" android:icon="#drawable/ic_search_black_24dp"/>
<item android:id="#+id/btn4" android:title="" android:icon="#drawable/ic_menu_black_24dp" />
</menu>
The UI is working perfectly ,it only requires some Listeners. I want if possible to use only BottomNavigationView.
This is how you set the listener:
val mOnNavigationItemSelectedListener = BottomNavigationView.OnNavigationItemSelectedListener { item ->
when (item.itemId) {
R.id.btn1 -> {
// put your code here
return#OnNavigationItemSelectedListener true
}
R.id.btn2 -> {
// put your code here
return#OnNavigationItemSelectedListener true
}
R.id.btn3 -> {
// put your code here
return#OnNavigationItemSelectedListener true
}
R.id.btn4 -> {
// put your code here
return#OnNavigationItemSelectedListener true
}
}
false
}
menuBar.setOnNavigationItemSelectedListener(mOnNavigationItemSelectedListener)
If menuBar is inside your activity's layout it does not need initialization.
If not, you must use findViewById() to initialize it.
I have a BottomSheet which houses a product detail card. The problem is, when I click on the + or - button on the product detail while the bottom sheet is in it's Expanded state, it jumps down.
When it is down and I click on the buttons it doesn't jump, it only happens when it is in it's Expanded (completely up) state
I have attached a GIF to show what is exactly happening
Here is the code
scan_sheet.xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout 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/bottom_sheet"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="bottom"
android:animateLayoutChanges="false"
android:background="#drawable/bottom_sheet_dialog_fragment"
android:orientation="vertical"
app:behavior_hideable="true"
app:behavior_peekHeight="100dp"
app:layout_behavior="studio.monotype.storedemo.BottomSheetBehavior">
<include
layout="#layout/hero_item"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="32dp"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.5"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<View
android:id="#+id/divider_view"
android:layout_width="match_parent"
android:layout_height="4dp"
android:layout_marginStart="24dp"
android:layout_marginTop="44dp"
android:layout_marginEnd="24dp"
android:background="#color/colorPrimary"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/hero_item" />
<include
layout="#layout/related_view"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="24dp"
android:layout_marginBottom="16dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintTop_toBottomOf="#+id/divider_view"
tools:layout_editor_absoluteX="0dp" />
</androidx.constraintlayout.widget.ConstraintLayout>
ScanActivity.kt (simplified to show only what is essential)
class ScanActivity : AppCompatActivity() {
private lateinit var bottomSheet: BottomSheetBehavior<*>
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_scan)
setupBottomSheet()
showSheet()
}
private fun setupBottomSheet() {
bottomSheet = BottomSheetBehavior.from(bottom_sheet)
bottomSheet.isHideable = true
bottomSheet.skipCollapsed= true
bottomSheet.isDraggable = true
bottomSheet.state = BottomSheetBehavior.STATE_HIDDEN
bottomSheet.addBottomSheetCallback(object : BottomSheetBehavior.BottomSheetCallback {
override fun onSlide(bottomSheet: View, slideOffset: Float) {
}
#SuppressLint("SwitchIntDef")
override fun onStateChanged(sheet: View, newState: Int) {
when (newState) {
BottomSheetBehavior.STATE_HIDDEN -> {
codeScanner.startPreview()
}
}
}
})
plus_btn.setOnClickListener {
var qty= qty_tv.text.toString().toInt()
qty++
qty_tv.text =qty.toString()
}
minus_btn.setOnClickListener {
var qty= qty_tv.text.toString().toInt()
if(qty!=0)
{
qty--
}
qty_tv.text =qty.toString()
}
}
private fun showSheet() {
bottomSheet.state = BottomSheetBehavior.STATE_EXPANDED
}
}
it seems that google engineer gave correct answer
Seems like something is going on because you are setting
android:layout_gravity="bottom" on the view with the
BottomSheetBehavior. You should remove that line.
It helped on my case
Looks to me like that could be a bug in the BottomSheetBehavior? Seems like the height of the sheet isn't getting saved or restored correctly. After the button is pressed, a layout happens again which changes the height. Could you file a bug at https://issuetracker.google.com/issues/new?component=439535