I have a navigation header as bellow
I want to update TextView in nav_header.xml from MainActivity.kt by Kotlin
I want to update text of TextView(id=drawer_user_name) from MainActivity.kt
main_activity.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="start">
<include
layout="#layout/content_main"
android:layout_width="match_parent"
android:layout_height="match_parent" />
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<androidx.recyclerview.widget.RecyclerView
android:id="#+id/recycler_view"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginTop="45dp"
android:background="#android:drawable/screen_background_light_transparent"
tools:listitem="#layout/item_list" />
</LinearLayout>
<com.google.android.material.navigation.NavigationView
android:id="#+id/nav_view"
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.drawerlayout.widget.DrawerLayout>
nav_header.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"
android:layout_width="match_parent"
android:layout_height="200dp"
android:background="#4cAF50"
android:orientation="vertical"
android:layout_gravity="top"
android:paddingTop="35dp"
android:paddingLeft="15dp"
android:paddingBottom="15dp"
android:id="#+id/ddd">
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="#mipmap/ic_launcher"
android:id="#+id/imageView"
android:layout_marginBottom="15dp"/>
<TextView
android:id="#+id/drawer_user_name" //--> i want to update this TextView from MainActivity.kt
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="title"
android:textColor="#FFFFFF"
android:textStyle="bold" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="this our navigation drawer"
android:textColor="#FFFFFF" />
</LinearLayout>
content_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"
android:orientation="vertical"
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.ActionBar">
<androidx.appcompat.widget.Toolbar
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/colorPrimary"
android:background="?attr/colorPrimary"
app:popupTheme="#style/ThemeOverlay.AppCompat.Light">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center_vertical"
android:orientation="horizontal">
<TextView
style="#style/TextAppearance.AppCompat.Widget.ActionBar.Title"
android:id="#+id/home_page_username"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Chat"
android:textColor="#FFFFFF" />
</LinearLayout>
</androidx.appcompat.widget.Toolbar>
</com.google.android.material.appbar.AppBarLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="this is my content"/>
</LinearLayout>
</LinearLayout>
Please Help me,I really need a way to solve this problem
thank you
Babbab forces us to write stories here to allow us to post a question(It looks like your post is mostly code; please add some more details)
Edit
my MainActivity.kt
package com.example.myapplication
...
import android.view.LayoutInflater
import android.widget.LinearLayout
import kotlinx.android.synthetic.main.activity_main_page.*
import kotlinx.android.synthetic.main.nav_header.view.*
class MainPageActivity : AppCompatActivity(), NavigationView.OnNavigationItemSelectedListener,CustomAdapter.OnItemClickListener {
lateinit var toolbar:androidx.appcompat.widget.Toolbar
lateinit var drawerLayout: DrawerLayout
lateinit var navView:NavigationView
private var data = arrayListOf<UserChanel>()
private lateinit var myadapter:CustomAdapter
private val gson = Gson()
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
toolbar =findViewById(R.id.toolbar)
setSupportActionBar(toolbar)
drawerLayout = findViewById(R.id.drawer_layout)
navView = findViewById(R.id.nav_view)
val toggle = ActionBarDrawerToggle(this,drawerLayout,toolbar,0,0)
drawerLayout.addDrawerListener(toggle)
toggle.syncState()
navView.setNavigationItemSelectedListener(this)
// val userNameTextView = nav_view.findViewById<TextView>(R.id.drawer_user_name)
// userNameTextView.text = "SOME TEXT" // error
nav_view.drawer_user_name.text = "SOME TEXT" // Error
val recyclerview = findViewById<RecyclerView>(R.id.recycler_view)
// for insert line divider to recyclerview items
recyclerview.addItemDecoration(SimpleDividerItemDecoration(this)) // for insert line divider to recyclerview items
send_request()
val adapter = CustomAdapter(this,data,this)
recyclerview.layoutManager = LinearLayoutManager(this)
recyclerview.adapter = adapter
recyclerview.setHasFixedSize(true)
myadapter = adapter
}
override fun onNavigationItemSelected(item: MenuItem): Boolean {
when(item.itemId){
R.id.nav_profile->{
Toast.makeText(this,"profile clicked",Toast.LENGTH_SHORT).show()
}
R.id.nav_message->{
Toast.makeText(this,"message clicked",Toast.LENGTH_SHORT).show()
}
R.id.nav_frinds->{
Toast.makeText(this,"frinds clicked",Toast.LENGTH_SHORT).show()
}
R.id.nav_update->{
Toast.makeText(this,"update clicked",Toast.LENGTH_SHORT).show()
}
R.id.nav_logout->{
Toast.makeText(this,"logout clicked",Toast.LENGTH_SHORT).show()
}
}
drawerLayout.closeDrawer(GravityCompat.START)
return true
}
private fun send_request(){
...
}
override fun onItemClick(position: Int,adapter: CustomAdapter,v:View) {
...
}
}
You can find the target view from its parent in your activity like either of these ways:
nav_view.getHeaderView(0).findViewById<TextView>(R.id.drawer_user_name).text = "SOME TEXT"
or
import kotlinx.android.synthetic.main.nav_header.view.*
...
nav_view.getHeaderView(0).drawer_user_name.text = "SOME TEXT"
It's possible to access the header view using getheaderview(int index) according to the documentation. As you have one header view in the NavigationView, it is accessible by index 0.
Related
I am loading the user profile image in a drawerlayout (with NavigationView) and the load happens in the MainActivity. The app keeps crashing with a null pointer error on the imageView for the profile Image but if I keep a null check the image does not load at all. The image is loaded from Firebase into drawer_profile_image
I don't know how to resolve this, I have tried multiple approaches but no solution works... cant understand the load sequence here. This primarily happens on launching the app post installation.
My code on the MainActivity
class MainActivity : AppCompatActivity(), NavigationView.OnNavigationItemSelectedListener {
var drawerLayout: DrawerLayout? = null
var toggle: ActionBarDrawerToggle? = null
var navigationView: NavigationView? = null
var firstItem: TabItem? = null
var secondItem: TabItem? = null
var adapter: MainPagerAdapter? = null
var refUsers: DatabaseReference? = null
var firebaseUser: FirebaseUser? = null
private lateinit var progressBar: ProgressDialog
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
val toolbar: Toolbar = findViewById(R.id.toolbar_main)
setSupportActionBar(toolbar)
supportActionBar!!.title = ""
val mTabLayout: TabLayout = findViewById(R.id.tab_layout)
val pager: ViewPager = findViewById(R.id.view_pager)
firstItem = findViewById(R.id.firstItem)
secondItem = findViewById(R.id.secondItem)
//Drawer
drawerLayout = findViewById(R.id.drawerLayout)
navigationView = findViewById(R.id.nav_view)
navigationView!!.setNavigationItemSelectedListener(this)
toggle = ActionBarDrawerToggle(this, drawerLayout, toolbar, R.string.open, R.string.close)
drawerLayout!!.addDrawerListener(toggle!!)
toggle!!.drawerArrowDrawable.color = resources.getColor(R.color.txtcolor)
toggle!!.isDrawerIndicatorEnabled = true
toggle!!.syncState()
//Swipe view pager
adapter = MainPagerAdapter(
supportFragmentManager,
FragmentPagerAdapter.BEHAVIOR_RESUME_ONLY_CURRENT_FRAGMENT,
mTabLayout!!.tabCount
)
pager.adapter = adapter
mTabLayout.addOnTabSelectedListener(object : TabLayout.OnTabSelectedListener {
override fun onTabSelected(tab: TabLayout.Tab) {
pager.currentItem = tab.position
}
override fun onTabUnselected(tab: TabLayout.Tab) {}
override fun onTabReselected(tab: TabLayout.Tab) {}
})
pager.addOnPageChangeListener(TabLayout.TabLayoutOnPageChangeListener(mTabLayout))
//To display fragments and to give a count of active chats
firebaseUser = FirebaseAuth.getInstance().currentUser
refUsers = FirebaseDatabase.getInstance().reference.child("Users").child(firebaseUser!!.uid)
val ref = FirebaseDatabase.getInstance().reference.child("Chats")
// //display the username and profile picture in Navigation Drawer
refUsers!!.addValueEventListener(object : ValueEventListener {
override fun onDataChange(p0: DataSnapshot) {
if (p0.exists()) {
val user: Users? = p0.getValue(Users::class.java)
//Store profile image in local DB
// Display of name on the main Page toolbar removed
Picasso.get().load(user!!.getProfile())
.placeholder(R.drawable.ic_baseline_whatshot_24_white).fit().centerCrop()
.into(
findViewById<ShapeableImageView>(R.id.drawer_profile_image)
)
val firstname = user.getFirstName()
val surname = user.getSurName()
val username = "$firstname $surname"
findViewById<TextView>(R.id.drawer_username).text = username
}
}
override fun onCancelled(p0: DatabaseError) {
}
})
DrawerLayout
<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:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true"
tools:openDrawer="start"
android:theme="#style/AppTheme.Material"
android:id="#+id/drawerLayout"
android:background="#color/white"
android:screenOrientation="portrait"
tools:context=".MainActivity">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
>
<com.google.android.material.appbar.AppBarLayout
android:id="#+id/MainAppBar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#color/white"
android:theme="#style/AppTheme.AppBarOverlay">
<androidx.appcompat.widget.Toolbar
android:id="#+id/toolbar_main"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
app:popupTheme="#style/AppTheme.PopupOverlay">
<TextView
android:id="#+id/homeTitle"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:text="Dashboard"
android:textColor="#color/txtcolor"
android:textSize="18sp"
android:textStyle="bold" />
<TextView
android:layout_width="10dp"
android:layout_height="10dp"
android:layout_gravity="end|top"
android:layout_marginEnd="5dp"
android:backgroundTint="#color/ColorRed"
android:background="#drawable/edittxtbg"/>
<ImageView
android:id="#+id/messages_dash"
android:layout_width="28dp"
android:layout_height="28dp"
android:layout_gravity="end"
android:src="#drawable/ic_mail" />
</androidx.appcompat.widget.Toolbar>
</com.google.android.material.appbar.AppBarLayout>
<androidx.viewpager.widget.ViewPager
android:id="#+id/view_pager"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_above="#+id/tab_layout"
android:layout_below="#+id/MainAppBar" />
<com.google.android.material.tabs.TabLayout
android:id="#+id/tab_layout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_gravity="bottom"
app:tabIconTint="#color/txtcolor"
android:background="#color/white"
app:tabIndicatorColor="#color/colorPrimaryDark"
app:tabTextColor="#color/txtcolor">
<com.google.android.material.tabs.TabItem
android:id="#+id/firstItem"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:icon="#drawable/ic_calendar_view" />
<com.google.android.material.tabs.TabItem
android:id="#+id/secondItem"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:icon="#drawable/ic_person" />
</com.google.android.material.tabs.TabLayout>
</RelativeLayout>
<com.google.android.material.navigation.NavigationView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/nav_view"
app:menu="#menu/drawnavmenu"
app:headerLayout="#layout/nav_header"
app:itemIconTint="#color/white"
android:background="#color/colorPrimaryDark"
app:itemTextColor="#color/white"
android:fitsSystemWindows="true"
android:visibility="visible"
android:layout_gravity="start">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="bottom"
android:clickable="true"
android:orientation="vertical">
<TextView
android:id="#+id/footer_item_1"
android:layout_width="match_parent"
android:layout_height="48dp"
android:gravity="center"
android:textSize="14sp"
android:textColor="#color/white"
android:layout_marginBottom="15dp"
android:text="powered by getLocal Solutions" />
</LinearLayout>
</com.google.android.material.navigation.NavigationView>
</androidx.drawerlayout.widget.DrawerLayout>
Error Log
Process: in.trial.trial, PID: 5282
java.lang.IllegalArgumentException: Target must not be null.
at com.squareup.picasso.RequestCreator.into(RequestCreator.java:682)
at com.squareup.picasso.RequestCreator.into(RequestCreator.java:665)
at in.trial.trial.MainActivity$onCreate$2.onDataChange(MainActivity.kt:112)
at com.google.firebase.database.core.ValueEventRegistration.fireEvent(ValueEventRegistration.java:75)
at com.google.firebase.database.core.view.DataEvent.fire(DataEvent.java:63)
at com.google.firebase.database.core.view.EventRaiser$1.run(EventRaiser.java:55)
at android.os.Handler.handleCallback(Handler.java:883)
at android.os.Handler.dispatchMessage(Handler.java:100)
at android.os.Looper.loop(Looper.java:224)
at android.app.ActivityThread.main(ActivityThread.java:7592)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:539)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:950)
Left drawer menu - profile image section
<LinearLayout
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<LinearLayout
android:id="#+id/navHeader"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:background="#color/white"
android:paddingTop="30dp"
android:paddingBottom="20dp"
android:gravity="center">
<com.google.android.material.imageview.ShapeableImageView
android:id="#+id/drawer_profile_image"
android:layout_width="80dp"
android:layout_height="80dp"
android:src="#drawable/ic_baseline_whatshot_24"
app:shapeAppearanceOverlay="#style/roundedcorner"
>
</com.google.android.material.imageview.ShapeableImageView>
<TextView
android:layout_width="wrap_content"
android:id="#+id/drawer_username"
android:layout_height="wrap_content"
android:textColor="#color/txtcolor"
android:textSize="18sp"
android:layout_marginTop="10dp"
/>
</LinearLayout>
Nav header section - included in NavigationView
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="#+id/navHeader"
android:layout_width="match_parent"
android:layout_height="200dp"
android:background="#color/white"
android:gravity="center"
android:orientation="vertical"
android:paddingTop="30dp"
android:paddingBottom="20dp">
<com.google.android.material.imageview.ShapeableImageView
android:id="#+id/drawer_profile_image"
android:layout_width="80dp"
android:layout_height="80dp"
android:layout_marginTop="15dp"
android:src="#drawable/ic_baseline_whatshot_24"
app:shapeAppearanceOverlay="#style/roundedcorner" />
<TextView
android:id="#+id/drawer_username"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:textColor="#color/txtcolor"
android:textSize="18sp"
android:textStyle="bold" />
</LinearLayout>
The issue was that the header in the navigationView was being loaded from another layout. Learned that I need to load that view by code first and resolved in the following way...below code was added in the MainActivity
val header: View = navigationView!!.getHeaderView(0)
val drawer_profile_image = header.findViewById<ShapeableImageView>(R.id.drawer_profile_image)
val username = header.findViewById<TextView>(R.id.drawer_username)
I am trying to add drawerlayout in my fragment home. I am getting java.lang.IllegalArgumentException: DrawerLayout must be measured with MeasureSpec.EXACTLY. this error when I tried to attach drawer layout to my fragment.
I have root layout as constraint layout. Firstly I tried with root layout as drawerlayout still I wast getting this exception so I tried adding constraint layout to it but did not work.
It works when I give the hard coded value to height and width as 500dp.
But hard coded value cant be given as it will not be good practice for all devices size it will differ.
Below is my code
drawer layout
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
xmlns:app="http://schemas.android.com/apk/res-auto"
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">
<androidx.drawerlayout.widget.DrawerLayout
android:id="#+id/drawer"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintTop_toTopOf="parent"
android:layout_width="match_parent"
android:layout_height="0dp"
android:fitsSystemWindows="true"
tools:openDrawer="start">
<include
layout="#layout/fragment_home"
android:visibility="visible" />
<com.google.android.material.navigation.NavigationView
android:id="#+id/nav_view"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true"
android:layout_gravity="start">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<include
android:id="#+id/nav_header"
layout="#layout/nav_header" />
<ScrollView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fadeScrollbars="true"
android:scrollbars="none">
<include
android:id="#+id/menuItems"
layout="#layout/layout_navigation_menu" />
</ScrollView>
</LinearLayout>
</com.google.android.material.navigation.NavigationView>
</androidx.drawerlayout.widget.DrawerLayout>
</androidx.constraintlayout.widget.ConstraintLayout>
Home fragment layout
<?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">
<ScrollView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:fillViewport="true"
android:fitsSystemWindows="true">
<androidx.constraintlayout.widget.ConstraintLayout
android:id="#+id/root"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<include android:id="#+id/app_bar"
layout="#layout/app_bar_main"/>
<RelativeLayout
android:id="#+id/relative_accept"
android:layout_width="match_parent"
android:layout_height="#dimen/margin_55"
android:orientation="horizontal"
android:background="#color/green_500"
app:layout_constraintTop_toBottomOf="#id/app_bar">
<androidx.appcompat.widget.AppCompatTextView
android:layout_width="wrap_content"
android:layout_alignParentStart="true"
android:layout_centerVertical="true"
android:textColor="#color/white"
android:layout_marginLeft="#dimen/margin_16"
android:layout_marginStart="#dimen/margin_16"
android:layout_marginRight="#dimen/margin_16"
android:layout_marginEnd="#dimen/margin_16"
android:text="#string/accepting_orders"
android:fontFamily="#font/roboto_regular"
android:textSize="#dimen/text_size_15"
android:layout_alignParentLeft="true"
android:layout_height="wrap_content" />
<Switch
android:id="#+id/switch1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:track="#drawable/switch_track_selector"
android:layout_centerVertical="true"
android:layout_alignParentEnd="true"
android:layout_alignParentRight="true"
tools:ignore="UseSwitchCompatOrMaterialXml" />
</RelativeLayout>
<FrameLayout
android:id="#+id/frameLayout_tab"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:clipToPadding="false"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/relative_accept">
<com.google.android.material.tabs.TabLayout
android:id="#+id/tabs"
android:layout_width="match_parent"
android:layout_height="42dp"
android:layout_marginStart="#dimen/margin_16"
android:layout_marginLeft="#dimen/margin_16"
android:layout_marginTop="#dimen/margin_20"
android:layout_marginEnd="#dimen/margin_16"
android:layout_marginRight="#dimen/margin_16"
android:background="#drawable/grey_drawable"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:tabGravity="fill"
app:tabIndicatorHeight="0dp"
app:tabMode="fixed"
android:onClick="#{(v)->click.onClick(v)}"
app:tabBackground="#drawable/tab_selector"
app:tabSelectedTextColor="#color/white" />
</FrameLayout>
<androidx.viewpager.widget.ViewPager
android:id="#+id/view_pager"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_constraintTop_toBottomOf="#+id/frameLayout_tab" />
</androidx.constraintlayout.widget.ConstraintLayout>
</ScrollView>
</androidx.constraintlayout.widget.ConstraintLayout>
Home fragment
class HomeFragment : BaseFragment() , View.OnClickListener{
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
}
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? = inflater.inflate(R.layout.drawer_layout_navigation_view, container, false)
override fun onActivityCreated(savedInstanceState: Bundle?) {
super.onActivityCreated(savedInstanceState)
init()
controlInit()
}
override fun init() {
val toggle = ActionBarDrawerToggle(
(activity as MainActivity),
drawer,
R.string.navigation_drawer_open,
R.string.navigation_drawer_close
)
drawer.addDrawerListener(toggle)
tabs.setupWithViewPager(view_pager)
bindViewPagerAdapter(view_pager, (activity as MainActivity))
bindViewPagerTabs(tabs, view_pager)
tabSettings()
}
private fun tabSettings() {
tabs.bringToFront()
view_pager.addOnPageChangeListener(object : ViewPager.OnPageChangeListener {
override fun onPageScrolled(
position: Int, positionOffset: Float, positionOffsetP: Int
) {
}
override fun onPageSelected(position: Int) {}
override fun onPageScrollStateChanged(i: Int) {}
})
}
private fun bindViewPagerAdapter(view: ViewPager?, mainActivity: MainActivity) {
val adapter = OrdersAdapter(view?.context!!, childFragmentManager)
view.adapter = adapter
}
private fun bindViewPagerTabs(view: TabLayout, pagerView: ViewPager?) {
view.setupWithViewPager(pagerView, true)
}
private fun controlInit() {
imageView_drawer.setOnClickListener(this)
}
#SuppressLint("WrongConstant")
override fun onClick(p0: View) {
when (p0.id) {
R.id.imageView_drawer -> {
drawer.openDrawer(Gravity.START)
}
}
}
companion object {
#JvmStatic
fun newInstance() =
HomeFragment().apply {}
}
}
Please help with this.Thank you....
Your layout actually worked just fine when I tested it so I am not sure if the issue lies with the layout. However your layout files are overly complex, you don't really need any of the nested layouts that you have and can achieve the same results without. ConstraintLayout was developed with the purpose of simplifying layout hierarchies so you should be able to just use that to organise your child views.
Also the NavigationView component is meant to be used to display a menu from a menu resource, not just to be used as a wrapper for your own. Either choose to display your own menu completely or use their implementation as intended. There is some nice documentation for this on the [Material Design website] here.
So may I suggest you try to cut down on nesting your layouts and then see whether this incidentally fixes your problem.
The hierarchy that you might want would probably look something like this:
drawer_layout.xml
<DrawerLayout>
<include layout="#layout/home" />
<NavigationView />
</DrawerLayout>
home.xml
<ScrollView>
<ConstraintLayout>
<include layout="#layout/app_bar_main"/>
<TextView />
<Switch />
<TabLayout />
<ViewPager />
</ConstraintLayout>
</ScrollView>
I am trying to Implement Navigation drawer but when I run my application and click on items in the drawer it just closes the drawer without doing showing the toast. nothing is happening with my drawer when I click an Item to navigate i.e The content inside Navigation Drawer is not clickable i.e the menu.
Below are my codes for Navigation drawer:
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="start">
<include
layout="#layout/content_menu"
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="start"
android:fitsSystemWindows="true"
app:headerLayout="#layout/nav_header"
app:menu="#menu/nav_menu"/>
<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=".FirstMain"
android:orientation="vertical"
android:gravity="center">
<TextView
android:layout_width="300dp"
android:layout_height="wrap_content"
android:layout_marginBottom="40dp"
android:background="#color/back"
android:fontFamily="#font/berkshire_swash"
android:gravity="center"
android:text="#string/app_name"
android:textAlignment="center"
android:textColor="#color/txt"
android:textSize="50sp"
android:textStyle="bold" />
<Button
android:id="#+id/button"
android:layout_width="165dp"
android:layout_height="wrap_content"
android:layout_margin="30sp"
android:background="#color/back"
android:fontFamily="#font/berkshire_swash"
android:gravity="center_horizontal"
android:padding="10sp"
android:text="PLAY"
android:textColor="#color/txt"
android:textSize="35sp"
android:textStyle="bold" />
</LinearLayout>
</androidx.drawerlayout.widget.DrawerLayout>
nav_menu.xml
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:android="http://schemas.android.com/apk/res/android">
<group android:checkableBehavior="single">
<item
android:id="#+id/nav_rule"
android:icon="#drawable/rules"
android:title="Rules" />
<item
android:id="#+id/nav_about"
android:icon="#drawable/about"
android:title="About"/>
</group>
</menu>
Content_menu.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"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<com.google.android.material.appbar.AppBarLayout
android:layout_height="wrap_content"
android:layout_width="match_parent"
android:theme="#style/ThemeOverlay.AppCompat.Dark.ActionBar">
<androidx.appcompat.widget.Toolbar
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="?attr/colorPrimary"
app:popupTheme="#style/ThemeOverlay.AppCompat.Light">
</androidx.appcompat.widget.Toolbar>
</com.google.android.material.appbar.AppBarLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:background="#drawable/puzzle">
</LinearLayout>
</LinearLayout>
Main.kt
class FirstMain : AppCompatActivity(), NavigationView.OnNavigationItemSelectedListener{
lateinit var btn : Button
lateinit var toolbar: Toolbar
lateinit var drawerLayout: DrawerLayout
lateinit var navView: NavigationView
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_first_main)
btn = findViewById(R.id.button)
toolbar = findViewById(R.id.toolbar)
setSupportActionBar(toolbar)
drawerLayout = findViewById(R.id.drawer_layout)
navView = findViewById(R.id.nav_view)
val toggle = ActionBarDrawerToggle(
this, drawerLayout, toolbar, 0, 0
)
drawerLayout.addDrawerListener(toggle)
toggle.syncState()
btn.setOnClickListener {
val intent = Intent(this, MainActivity::class.java)
startActivity(intent)
}
navView.setNavigationItemSelectedListener(this)
}
override fun onNavigationItemSelected(p0: MenuItem): Boolean {
p0.isChecked = true
when (p0.itemId) {
R.id.nav_rule -> {
Toast.makeText(this, "Profile clicked", Toast.LENGTH_LONG).show()
}
R.id.nav_about -> {
Toast.makeText(this, "Messages clicked", Toast.LENGTH_LONG).show()
}
}
drawerLayout.closeDrawer(GravityCompat.START)
return true
}
}
Your code looks all good, weird it doesn't work but you can try and add
navView.bringToFront();
navView.setNavigationItemSelectedListener(this)
When I added DrawerToggle(Hamburger) by using kotlin, the ImageView (TravelPocket) moved to right.
So, it is not in center..
I want to make it move to center not using margin or padding property.
below is my image.
problem image
activity_main.xml
<androidx.drawerlayout.widget.DrawerLayout
android:id="#+id/drawer"
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">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="48dp">
<androidx.appcompat.widget.Toolbar
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:layout_alignParentTop="true"
android:background="#color/colorPrimary"
app:contentInsetStart="0dp">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<ImageView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:paddingTop="8dp"
android:paddingBottom="14dp"
android:src="#drawable/ic_logo"/>
</RelativeLayout>
</androidx.appcompat.widget.Toolbar>
</RelativeLayout>
MainActivity.class
class MainActivity : AppCompatActivity() {
lateinit var drawerToggle: ActionBarDrawerToggle
var currentTime: Long = 0
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
drawerToggle = ActionBarDrawerToggle(this, drawer, toolbar,0,0)
drawer.addDrawerListener(drawerToggle)
drawerToggle.syncState()
}
}
I'm currently working on the home screen of my app and am using fragments to load the different "pages" when a user clicks on a button on a bottom navigation bar. What I've found is that when I load the home screen the bottom bar seems to reload itself again, creating two bars, one in the middle of the page and one in the proper position at the bottom of the screen (while the middle bar isn't actually functional). I'm thinking that the fragment loading in the activity is the cause, but I'm not entirely sure on how to solve it. Below is an image of the problem as well as some of the code that I've got.
activity_home.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:design="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/home_screen"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true">
<include
layout="#layout/app_bar"
android:layout_width="0dp"
android:layout_height="0dp"
tools:ignore="MissingConstraints"
tools:layout_editor_absoluteX="0dp"
tools:layout_editor_absoluteY="225dp" />
<android.support.v4.widget.NestedScrollView
android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<FrameLayout
android:id="#+id/fragment_container"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</LinearLayout>
</android.support.v4.widget.NestedScrollView>
<FrameLayout
android:id="#+id/frame_layout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="bottom"
android:background="#f1f1f1"
tools:layout_editor_absoluteX="8dp"
tools:layout_editor_absoluteY="25dp">
<View
android:layout_width="match_parent"
android:layout_height="2dp"
android:background="#drawable/shadow" />
<android.support.design.widget.BottomNavigationView
android:id="#+id/bottom_nav"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="start"
design:menu="#menu/bottom_nav_menu"
/>
</FrameLayout>
</android.support.design.widget.CoordinatorLayout>
home_fragment.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:design="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/home_fragment"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<android.support.constraint.ConstraintLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:layout_editor_absoluteX="0dp"
tools:layout_editor_absoluteY="0dp">
<ImageView
android:id="#+id/tokyo_placeholder"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:adjustViewBounds="true"
android:scaleType="fitStart"
design:layout_constraintLeft_toLeftOf="parent"
design:layout_constraintRight_toRightOf="parent"
design:layout_constraintTop_toTopOf="parent"
design:srcCompat="#drawable/main_screen_placeholder" />
<ImageView
android:id="#+id/airplane_icon"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginBottom="8dp"
android:layout_marginEnd="8dp"
android:layout_marginLeft="8dp"
android:layout_marginRight="8dp"
android:layout_marginStart="8dp"
android:layout_marginTop="8dp"
android:background="#drawable/circle_background"
design:layout_constraintBottom_toBottomOf="#+id/tokyo_placeholder"
design:layout_constraintLeft_toLeftOf="#+id/tokyo_placeholder"
design:layout_constraintRight_toRightOf="#+id/tokyo_placeholder"
design:layout_constraintTop_toTopOf="#+id/tokyo_placeholder"
design:srcCompat="#drawable/icons8_airplane_48" />
<include
layout="#layout/app_bar"
android:layout_width="0dp"
android:layout_height="0dp"
tools:ignore="MissingConstraints"
tools:layout_editor_absoluteX="0dp"
tools:layout_editor_absoluteY="225dp" />
<TableLayout
android:layout_width="349dp"
android:layout_height="0dp"
android:layout_marginTop="8dp"
android:orientation="horizontal"
design:layout_constraintLeft_toLeftOf="parent"
design:layout_constraintRight_toRightOf="parent"
design:layout_constraintTop_toBottomOf="#+id/tokyo_placeholder">
<TableRow
android:layout_width="match_parent"
android:layout_height="wrap_content">
<TextView
android:id="#+id/destination_headline"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:fontFamily="sans-serif"
android:text="Featured Destinations"
android:textAllCaps="true"
android:textAppearance="#style/TextAppearance.AppCompat.Headline"
android:textSize="14sp"
android:textStyle="bold" />
</TableRow>
<TableRow
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:layout_editor_absoluteX="8dp"
tools:layout_editor_absoluteY="8dp">
<HorizontalScrollView
android:id="#+id/horizontal_scroll"
android:layout_width="match_parent"
android:layout_height="wrap_content"
tools:layout_editor_absoluteX="8dp"
tools:layout_editor_absoluteY="8dp">
<LinearLayout
android:id="#+id/featured_destinations_gallery"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal" >
</LinearLayout>
</HorizontalScrollView>
</TableRow>
<TableRow
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="#+id/saved_trips_headline"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:fontFamily="sans-serif"
android:text="Saved Trips"
android:textAllCaps="true"
android:textAppearance="#style/TextAppearance.AppCompat.Headline"
android:textSize="14sp"
android:textStyle="bold" />
</TableRow>
</TableLayout>
</android.support.constraint.ConstraintLayout>
<FrameLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="bottom">
<View
android:layout_width="match_parent"
android:layout_height="4dp"
android:background="#drawable/shadow" />
<android.support.design.widget.BottomNavigationView
android:id="#+id/bottom_nav"
elevation="8dp"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="bottom"
design:menu="#menu/bottom_nav_menu" />
</FrameLayout>
<!-- TODO: Make page scrollable and fix bottom navigation bar -->
</android.support.design.widget.CoordinatorLayout>
HomeActivity.kt
package projectrc_android.project_rc
import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import android.support.design.widget.BottomNavigationView
import android.support.v7.widget.Toolbar
import projectrc_android.project_rc.R.*
class HomeActivity : AppCompatActivity() {
private var current_fragment = id.home_fragment
private val fragmentManager = supportFragmentManager
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(layout.activity_home)
val toolbar = findViewById(R.id.app_bar) as Toolbar
setSupportActionBar(toolbar)
supportActionBar?.setDisplayShowTitleEnabled(false)
val bottomNavigationBar = findViewById(id.bottom_nav) as BottomNavigationView // get bottom navigation bar
bottomNavigationBar.selectedItemId = R.id.home_button // set the selected menu item to home at the start
ShowFragment(R.id.home_button) // load the home fragment item into the activity
var selectedMenuItem = bottomNavigationBar.selectedItemId // get currently selected menu item
bottomNavigationBar.setOnNavigationItemSelectedListener { item ->
if(item.itemId != selectedMenuItem) { // if the user picks a button that's NOT the currently selected one
selectedMenuItem = item.itemId // update the selected menu item
ShowFragment(item.itemId)
}
true
}
}
private fun ShowFragment(menuButton: Int) {
val transaction = fragmentManager.beginTransaction()
when (menuButton) {
R.id.home_button -> {
transaction.replace(R.id.fragment_container, HomeFragment())
current_fragment = R.id.home_fragment
}
R.id.inbox_button -> {
transaction.replace(R.id.fragment_container, InboxFragment())
current_fragment = R.id.inbox_fragment
}
R.id.account_button -> {
transaction.replace(R.id.fragment_container, AccountFragment())
current_fragment = R.id.account_fragment
}
}
transaction.addToBackStack(null)
transaction.commit()
}
}
HomeFragment.kt
package projectrc_android.project_rc
import android.support.v4.app.Fragment;
import android.content.Context
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.LinearLayout
import android.widget.ImageView
import com.bumptech.glide.Glide
import com.bumptech.glide.request.RequestOptions
class HomeFragment : Fragment() {
private val imagePaths = intArrayOf(R.drawable.cuba_placeholder, R.drawable.s_korea_placeholder,
R.drawable.greece_placeholder, R.drawable.san_francisco_placeholder, R.drawable.cuba_placeholder, R.drawable.s_korea_placeholder,
R.drawable.greece_placeholder, R.drawable.san_francisco_placeholder)
override fun onCreateView(inflater: LayoutInflater?, container: ViewGroup?, savedInstanceState: Bundle?): View {
var view = inflater!!.inflate(R.layout.home_fragment, container, false)
val destinationGallery = view.findViewById(R.id.featured_destinations_gallery) as LinearLayout
//set up toolbar in place of action bar (and remove title)
//dynamically add images to scrollview
addImageToLayout(view.context, destinationGallery, imagePaths, 260, 360)
return view
}
private fun addImageToLayout(context : Context, layout: LinearLayout, imagePaths: IntArray, width: Int, height: Int) {
val numberOfImages = imagePaths.size
for (index in 0 until numberOfImages) {
val imageView = ImageView(context)
imageView.id = index
imageView.setPadding(2, 2, 2, 2)
Glide
.with(this)
.load(imagePaths[index])
.apply(RequestOptions()
.override(width, height)
.centerCrop())
.into(imageView)
layout.addView(imageView)
}
}
}
You have added android.support.design.widget.BottomNavigationView in both activity_home.xml as well as in home_fragment.xml. So you are seeing two bottom navigation views.
you have set listener to the activity's navigation view But didn't set any listener to the fragment's navigation view and so the one that is shown in the middle is not functional.
Remove navigation view from home_fragment.xml. It should solve the issue.