I am trying to create modal bottom sheet dialog to show a list of items which will be scrollable.
dialog_bottom_example.xml:
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#color/white"
xmlns:app="http://schemas.android.com/apk/res-auto">
<LinearLayout
android:id="#+id/container"
android:layout_width="0dp"
android:layout_height="0dp"
android:orientation="vertical"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintBottom_toBottomOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>
Items in LinearLayout is getting added dynamically based on list size as below:
ExampleDialogBottom:
class ExampleDialogBottom: BottomSheetDialogFragment() {
private lateinit var binding: DialogExampleBinding
private var skusItems = mutableListOf<SkuItem>();
companion object {
internal const val TAG = "ExampleDialogBottom"
#JvmStatic
fun newInstance(nonEligibleErxItem: NonEligibleErxItem) = NonEligibleBottomDialog
}
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
binding = DialogExampleBinding.inflate(inflater, container, false)
return binding.root
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
configureSkuItems()
}
private fun configureSkuItems() {
if (!skuItems.isNullOrEmpty()) {
val inflater = LayoutInflater.from(context)
for (sku in skuItems) {
val skuItemView = SingleSkuItemViewBinding.inflate(inflater, null, false)
skuItemView.skuImage.setImageWithVisibility(sku.imageUrl)
skuItemView.skuTitle.setTextWithVisibility(sku.name)
binding.container.addView(skuItemView.root)
}
binding.container.visibility = View.VISIBLE
} else {
binding.container.visibility = View.GONE
}
}
ExmpaleActivity:
button.setOnClickListener {
ExampleDialogBottom.newInstance().show(getSupportFragmentManager(),
ExampleDialogBottom.TAG);
}
However, when I click on button, a transparent dialog shows up, no content is showing.
When I removed match-contraint and changed it match-parent or wrap-content, it's working as expected.
It would be great if someone could help? Thanks in advance.
Related
Hi I have an simple app with Bottom Navigation Activity. In Home Fragment I have a Button called Fruits. It opens a PopupWindow. In the popup is a RecyclerView with 4 Buttons(fruits names).
I want, when I press on a Button in the PopupWindow, to change the name of Button(called Fruits) form home_fragment, in whatever fruit was chosen.
HomeFragment:
class HomeFragment : Fragment() {
private var _binding: FragmentHomeBinding? = null
private val binding get() = _binding!!
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View {
_binding = FragmentHomeBinding.inflate(inflater, container, false)
val root: View = binding.root
return root
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
binding.Fruits.setOnClickListener {
show_popup(requireContext(), view, R.layout.fruits_popup)
}
}
override fun onDestroyView() {
super.onDestroyView()
_binding = null
}
fun show_popup(c: Context, v: View, l: Int){
val popup_window = PopupWindow(c)
val inflater = layoutInflater.inflate(l, null)
val recyclerView: RecyclerView = inflater.findViewById(R.id.recycler_view)
recyclerView.layoutManager = LinearLayoutManager(context)
recyclerView.adapter = FruitsAdapter()
popup_window.contentView = inflater
popup_window.isFocusable = true
popup_window.isOutsideTouchable = true
popup_window.showAtLocation(v, Gravity.CENTER, 0, 0)
}
}
FruitsAdapter:
class FruitsAdapter : RecyclerView.Adapter<FruitsAdapter.FruitsViewHolder>() {
private val list = listOf<String>("Banana", "Orange", "Apple", "Watermelon")
class FruitsViewHolder(val view: View): RecyclerView.ViewHolder(view) {
val button = view.findViewById<Button>(R.id.fruit)
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): FruitsViewHolder {
val layout = LayoutInflater.from(parent.context).inflate(R.layout.fruit, parent, false)
return FruitsViewHolder(layout)
}
override fun onBindViewHolder(holder: FruitsViewHolder, position: Int) {
val item = list.get(position)
holder.button.text = item.toString()
}
override fun getItemCount(): Int {
return list.size
}
}
fragment_gome.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"
tools:context=".ui.home.HomeFragment">
<Button
android:id="#+id/Fruits"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Fruits"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.498"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.254" />
</androidx.constraintlayout.widget.ConstraintLayout>
fruits_popup.xml:
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout 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">
<androidx.recyclerview.widget.RecyclerView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/recycler_view"/>
</FrameLayout>
fruit.xml
<?xml version="1.0" encoding="utf-8"?>
<Button xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/fruit"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="4dp"
android:padding="8dp" />
Try to google with keyword 'callback' bro
I want to move a ConstraintLayout programmatically. I looked through some solutions on stack overflow but they didn't work for me.
There are two ConstraintLayouts placed vertically. When the code goes into else if("android.permission.CAMERA" in permissionList.toString(), the above constraint layout (layoutLocation) will be invisible and the below constraint layout (layoutCamera) will come up and take its position. I mark where I should use declare it with 'want to use here'.
Code (apology to not ba able to post the whole code due to patent reason)
class SplashFragment : Fragment() {
private lateinit var mContext: MainActivity
private lateinit var binding : FragmentSplashBinding
private val viewModel : SplashViewModel by inject()
private val getPermissionUseCase : GetPermissionUseCase by inject()
override fun onAttach(context: Context) {
super.onAttach(context)
mContext = context as MainActivity
}
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?
): View {
binding = DataBindingUtil.inflate(inflater, R.layout.fragment_splash, container, false)
return binding.root
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
binding.viewModel = viewModel
binding.lifecycleOwner = viewLifecycleOwner
}
private fun actionApplicationSetting(permissionList : List<String>) {
val layoutInflater = LayoutInflater.from(context)
val view = layoutInflater.inflate(R.layout.dialog_splash, null)
val alertDialog = AlertDialog.Builder(requireContext(), R.style.CustomAlertDialog).setView(view).create()
val layoutLocation : ConstraintLayout = view.findViewById(R.id.layout_box_location)
val layoutCamera : ConstraintLayout = view.findViewById(R.id.layout_box_camera)
for(permission in permissionList) {
if("android.permission.CAMERA" in permissionList.toString() && "android.permission.ACCESS_COARSE_LOCATION" in permissionList.toString()) {
layoutLocation.background = AppCompatResources.getDrawable(mContext, R.drawable.auth_level_blue)
layoutCamera.background = AppCompatResources.getDrawable(mContext, R.drawable.auth_level_blue)
}else if("android.permission.ACCESS_COARSE_LOCATION" in permissionList.toString()) {
layoutLocation.background = AppCompatResources.getDrawable(mContext, R.drawable.auth_level_blue)
}else if("android.permission.CAMERA" in permissionList.toString()) {
layoutLocation.visibility = View.INVISIBLE
// want to use here
}
}
alertDialog.show()
}
}
XML
<?xml version="1.0" encoding="utf-8"?>
<layout 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">
<androidx.constraintlayout.widget.ConstraintLayout
android:id="#+id/layout_main"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<androidx.constraintlayout.widget.ConstraintLayout
android:layout_width="wrap_content"
android:layout_height="60dp"
android:layout_marginStart="70dp"
android:layout_marginBottom="10dp"
app:layout_constraintBottom_toBottomOf="#+id/layout_wrapper"
app:layout_constraintEnd_toEndOf="#+id/layout_wrapper"
app:layout_constraintStart_toStartOf="#+id/layout_wrapper">
</androidx.constraintlayout.widget.ConstraintLayout>
<androidx.constraintlayout.widget.ConstraintLayout
android:id="#+id/layout_wrapper"
android:layout_width="match_parent"
android:layout_height="180dp"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent">
<androidx.constraintlayout.widget.ConstraintLayout
android:id="#+id/layout_box_location"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<androidx.constraintlayout.widget.ConstraintLayout
android:id="#+id/layout_box_camera"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/layout_box_location" />
</androidx.constraintlayout.widget.ConstraintLayout>
</androidx.constraintlayout.widget.ConstraintLayout>
</layout>
Instead of layoutLocation.visibility = View.INVISIBLE try layoutLocation.visibility = View.GONE
In one of my app, I am using Android Navigation Architecture component. Everything was going fine and smooth. But when I wanted to navigate to DialogFrgment, I got stuck. Though DialogFragment triggered, but no layout is seen. Just visible the overlap blur background. Can't figure out the actual problem. Here is the code I use to display dialogFragment.
This is custom layout I wanted to show
terms_and_condition.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="wrap_content"
tools:ignore="WebViewLayout">
<LinearLayout
android:id="#+id/linearLayout6"
android:layout_width="match_parent"
android:layout_height="#dimen/_60sdp"
android:background="#color/colorAccent"
android:gravity="center_vertical"
android:orientation="horizontal"
android:weightSum="4"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent">
<com.google.android.material.textview.MaterialTextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="#dimen/_20sdp"
android:layout_weight="3"
android:text="#string/terms_amp_conditions"
android:textSize="#dimen/_15ssp"
android:textStyle="bold"
android:textColor="#color/white" />
<androidx.appcompat.widget.AppCompatImageView
android:id="#+id/close_privacy_policy_dialog_image_view"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:src="#drawable/ic_close" />
</LinearLayout>
<WebView
android:id="#+id/privacy_policy_web_view"
android:layout_width="match_parent"
android:layout_height="#dimen/_300sdp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.0"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/linearLayout6"
app:layout_constraintVertical_bias="0.0" />
</androidx.constraintlayout.widget.ConstraintLayout>
This is the base class for Dialog fragment
BaseDialogFragment.kt
abstract class BaseDialogFragment : DaggerAppCompatDialogFragment() {
#LayoutRes
abstract fun getLayoutResource(): Int
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
return container?.inflate(getLayoutResource())
}
override fun onCreateDialog(savedInstanceState: Bundle?): Dialog {
val dialog = super.onCreateDialog(savedInstanceState)
dialog.window?.let {
it.requestFeature(FEATURE_NO_TITLE)
it.setBackgroundDrawableResource(R.color.transparent)
}
return dialog
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
dialog?.window?.setLayout(
MATCH_PARENT,
WRAP_CONTENT
)
}
protected fun disableDismissOnBackPress() {
dialog?.setOnKeyListener { _, keyCode, event ->
if (keyCode == KEYCODE_BACK) {
if (event.action != ACTION_DOWN) true else true
} else {
false
}
}
}
}
TermsAndConditionDialogFragment.kt
class TermsAndConditionDialogFragment: BaseDialogFragment() {
override fun getLayoutResource() = R.layout.dialog_terms_and_condition
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
val closeTheDialogImageView = view.findViewById<ImageView>(R.id.close_privacy_policy_dialog_image_view)
val privacyPolicyWebView = view.findViewById<WebView>(R.id.privacy_policy_web_view)
privacyPolicyWebView.loadUrl("file:///android_asset/privacy_policy.html")
closeTheDialogImageView.setOnClickListener { dialog?.dismiss() }
}
}
navigation_graph.xml
<navigation
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/navigation_graph"
app:startDestination="#id/splashFragment">
<dialog
android:id="#+id/termsAndConditionDialogFragment"
android:name="com.aomi.mybase.ui.feature.termAndCondition.TermsAndConditionDialogFragment"
tools:layout="#layout/dialog_terms_and_condition"/>
</navigation>
SignUpFragment.kt
terms_and_condition_button.setOnClickListener {
findNavController().navigate(R.id.termsAndConditionDialogFragment)
}
Change your onCreateDialog like below and replace your DaggerAppCompatDialogFragment to DialogFragment
override fun onCreateDialog(savedInstanceState: Bundle?): Dialog {
return this.activity?.let {
val builder = AlertDialog.Builder(it)
val inflater = requireActivity().layoutInflater
val layoutId: Int = R.layout.your_layout
val rootView = inflater.inflate(layoutId, null)
builder.setView(rootView)
val alertDialog = builder.create()
alertDialog.window?.setBackgroundDrawableResource(android.R.color.transparent)
alertDialog
} ?: throw IllegalStateException("Activity cannot be null")
}
You can also use DaggerAppCompatDialogFragment when use Dagger2 as Dependency Injection. Here is the code
class TermsAndConditionDialogFragment: DaggerAppCompatDialogFragment() {
override fun onCreateDialog(savedInstanceState: Bundle?): Dialog {
val rootView = requireActivity().layoutInflater.inflate(R.layout.dialog_terms_and_condition, null)
initWidget(rootView)
return this.activity?.let {
val dialog = AlertDialog.Builder(it).setView(rootView).create()
dialog.window?.let { window ->
window.setLayout(MATCH_PARENT, WRAP_CONTENT)
window.requestFeature(FEATURE_NO_TITLE)
window.setBackgroundDrawableResource(R.color.transparent)
}
dialog
} ?: throw IllegalStateException("Activity cannot be null")
}
private fun initWidget(view: View) {
val closeTheDialogImageView = view.findViewById<ImageView>(R.id.close_privacy_policy_dialog_image_view)
val privacyPolicyWebView = view.findViewById<WebView>(R.id.privacy_policy_web_view)
privacyPolicyWebView.loadUrl("file:///android_asset/terms_and_condition.html")
closeTheDialogImageView.setOnClickListener { dialog?.dismiss() }
}
}
Do fragment need a very precise way of handling the texts that are set in the xml of the fragment ?
I had two times very similar problems : text written in xml cannot be updated properly.
Here is my first fragment. I previously had a foolish text written in the xml for the textview 'msg2ndfragment'. The issue I had was that during the onViewCreated, the text sent by the new Activity to the text would overlap the foolish text written in the Xml.
So I removed the foolish text, and now it is fine. (I could update thee text three times in a row it would work as long as the text was not initially defined in the xml),
class SecondFragment : Fragment() {
//Passer par new instance pour créé le fragment en lui donnant le nom à afficher
companion object {
fun newInstance(title: String?): SecondFragment {
val fragmentSecond = SecondFragment()
val args = Bundle()
args.putString(MainActivity.MESSAGE_SECOND_ACTIVITE, title)
fragmentSecond.arguments = args
return fragmentSecond
}
}
private lateinit var viewModel: SecondViewModel
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View {
return inflater.inflate(R.layout.second_fragment, container, false)
}
override fun onActivityCreated(savedInstanceState: Bundle?) {
super.onActivityCreated(savedInstanceState)
viewModel = ViewModelProviders.of(this).get(SecondViewModel::class.java)
val message = arguments!!.getString(MainActivity.MESSAGE_SECOND_ACTIVITE, "")
val aries = view?.findViewById<TextView>(R.id.msg2ndfragment);
aries?.text = message
}
}
But now, I have a very similar issue: in a different fragment in another activity I have an editText with a hint. I want to make the hint disappear. Same issue : if the hint is written in the Xml : any text written by the user will only overlap the old text. If I initially define the hint dynamically, the hint disappears when the user starts writing.
class MainFragment : Fragment() {
companion object {
fun newInstance() = MainFragment()
}
private lateinit var viewModel: MainViewModel
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View {
return inflater.inflate(R.layout.main_fragment, container, false)
}
override fun onActivityCreated(savedInstanceState: Bundle?) {
super.onActivityCreated(savedInstanceState)
viewModel = ViewModelProviders.of(this).get(MainViewModel::class.java)
val aries = view?.findViewById<Button>(R.id.btnGo2ndActivity);
aries?.setOnClickListener { onGoSecondFragmentClick(it) }
Log.d("p1", "p1");
//Faire disparaitre le int au touch car cela ne se fait pas automatiquement
val edTxtTo2nd = view?.findViewById<EditText>(R.id.edt2ndActEditText)
edTxtTo2nd?.hint = "a"
Log.d("pouf", "pouf");
/*val edTxtTo2nd = view?.findViewById<EditText>(R.id.edt2ndActEditText)
edTxtTo2nd?.setOnClickListener(View.OnClickListener { v ->
edTxtTo2nd?.setHint("")
}) */
}
private var listener: onMvmtClickListener? = null
public interface onMvmtClickListener {
fun onNextActivityClick(name1: String)
}
// Store the listener (activity) that will have events fired once the fragment is attached
override fun onAttach(context: Context) {
super.onAttach(context)
if (context is onMvmtClickListener) {
listener = context as onMvmtClickListener
} else {
throw ClassCastException(
"$context must implement nMvmtClickListener"
)
}
}
fun onGoSecondFragmentClick(v: View?) {
val nom = view?.findViewById<EditText>(R.id.edt2ndActEditText);
listener?.onNextActivityClick(nom?.text.toString())
}
}
<?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/main"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".ui.main.MainFragment">
<TextView
android:id="#+id/message"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/hello_world"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<Button
android:id="#+id/btnGo2ndActivity"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="21dp"
android:text="#string/go_to_2nd_act"
app:layout_constraintTop_toBottomOf="#+id/edt2ndActEditText"
tools:layout_editor_absoluteX="111dp"
tools:ignore="MissingConstraints" />
<EditText
android:id="#+id/edt2ndActEditText"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="35dp"
android:layout_marginBottom="21dp"
android:ems="10"
android:inputType="textPersonName"
app:layout_constraintBottom_toTopOf="#+id/btnGo2ndActivity"
app:layout_constraintTop_toTopOf="#+id/message"
tools:layout_editor_absoluteX="95dp"
tools:ignore="MissingConstraints" />
</androidx.constraintlayout.widget.ConstraintLayout>
Edit : here are the main_activity kotelin and xml
class MainActivity : AppCompatActivity(), MainFragment.onMvmtClickListener {
companion object{
const val MESSAGE_SECOND_ACTIVITE = "Message.s
econd.activite"
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.main_activity)
if (savedInstanceState == null) {
supportFragmentManager.beginTransaction()
.replace(R.id.container, MainFragment.newInstance())
.commitNow()
}
}
override fun onNextActivityClick(name1: String) {
var intent = Intent(this, SecondActivity::class.java)
intent.putExtra(MESSAGE_SECOND_ACTIVITE, name1)
startActivity(intent)
}
}
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id
/container"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity" >
<fragment
android:id="#+id/fragment"
android:name="com.example.myapplication.ui.main.MainFragment"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</FrameLayout>
Using this workaround to define any text or hint feels wrong to me. How can I define them in the Xml of the fragment without having this overlap issue ?
Thank you in advance for any help.
I am writing setOnClickListener for Button in Fragment in Kotlin, but it is not working and says "NullPointerException" in Fragment where btnAdd used row.
class TODOFragment : Fragment() {
private var works = ArrayList<WorkData>()
override fun onCreateView(inflater: LayoutInflater, container:
ViewGroup?, savedInstanceState: Bundle?): View? {
val view = inflater.inflate(R.layout.work_list, container, false)
view.work_list.layoutManager = LinearLayoutManager(context)
works = Database.database().getWorksByStatus(3)
val adapter = WorkAdapter(works)
view.work_list.adapter = adapter
btnAdd.setOnClickListener {
val dialog = AddProductDialog(context!!)
dialog.setOnClickListener { title, description ->
Database.database().addWork(title, description)
adapter.data.add(WorkData(title, description, Status.TODO))
}
dialog.show()
adapter.notifyItemInserted(works.size + 1)
work_list.layoutManager!!.scrollToPosition(adapter.itemCount)
}
return view
}
}
Here is my activity_main
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout 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"
tools:context=".MainActivity">
<android.support.design.widget.TabLayout
android:id="#+id/tabLayout"
android:layout_width="match_parent"
android:layout_height="?actionBarSize">
</android.support.design.widget.TabLayout>
<android.support.v4.view.ViewPager
android:id="#+id/pager"
android:layout_width="match_parent"
android:layout_height="match_parent">
</android.support.v4.view.ViewPager>
<ImageButton
android:id="#+id/btnAdd"
android:layout_width="64dp"
android:layout_height="64dp"
android:layout_gravity="bottom|right"
android:layout_margin="32dp"
android:background="#drawable/btn_circle_bgn"
android:src="#drawable/ic_add"
tools:ignore="RtlHardcoded" />
</FrameLayout>
I can't understand What am I doing wrong here
Your button is part of the inflated view.
To get hold of it you need to use it within it's view, as bellow :
override fun onCreateView(inflater: LayoutInflater, container:
ViewGroup?, savedInstanceState: Bundle?): View? {
val view = inflater.inflate(R.layout.work_list, container, false)
view.work_list.layoutManager = LinearLayoutManager(context)
works = Database.database().getWorksByStatus(3)
val adapter = WorkAdapter(works)
view.work_list.adapter = adapter
view.btnAdd.setOnClickListener {
val dialog = AddProductDialog(context!!)
dialog.setOnClickListener { title, description ->
Database.database().addWork(title, description)
adapter.data.add(WorkData(title, description, Status.TODO))
}
dialog.show()
adapter.notifyItemInserted(works.size + 1)
work_list.layoutManager!!.scrollToPosition(adapter.itemCount)
}
return view
}
If you are not using the kotlin android extensions plugin, you will need to find the button using something like.
btnAdd = view.findViewById(R.id.btnAdd) as Button
before calling the setOnClickListener method
The same applies to any other view item defined in XML.