I capture Key Events (from an external keyboard) within my App. I use onKeyDown() method from Activity. In my app I switch between different Fragments. If I am in a normal Fragment then Activity's onKeyDown() is triggered when pressing buttons. But when I use a DialogFragment as a Dialog then pressing the button does not trigger Activity'sonKeyDown()` any more.
Here some sample code:
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
}
fun onClick(view: View) {
// a) Key Event works if adding it via a fragment transaction by my own
// val fragment = MyDialogFragment.newInstance()
// val fragmentTransaction = supportFragmentManager.beginTransaction()
// fragmentTransaction.add(R.id.fr_container, fragment, fragment.javaClass.name)
// fragmentTransaction.commit()
// b) Key Event doesn't work if showing as a dialog
val fragment = MyDialogFragment.newInstance()
fragment.show(supportFragmentManager, fragment.javaClass.name)
}
override fun onKeyDown(keyCode: Int, event: KeyEvent?): Boolean {
Log.i(javaClass.name, "onKeyDown() keyCode: $keyCode")
return true
}
}
And my two fragments:
class MyNormalFragment : Fragment() {
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
return inflater.inflate(R.layout.fragment_my_normal, container, false)
}
}
class MyDialogFragment : DialogFragment() {
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
return inflater.inflate(R.layout.fragment_my_dialog, container, false)
}
companion object {
fun newInstance() = MyDialogFragment()
}
}
As soon as I call a) show() to open the MyDialogFragment then the key events are not captured any more. But if I open MyDialogFragment b) via custom Fragments transaction then the key events are still captured, but my Fragment isn't shown as a Dialog any more.
What do I have to do to let the event also trigger when my dialog is displayed?
Ridcully's answer is right. I just wanted to post what I changed inside MyDialogFragment to keep on capturing key events:
class MyDialogFragment : DialogFragment() {
private val keyEventListener = DialogInterface.OnKeyListener { dialog, keyCode, event ->
Log.i(javaClass.name, "onKey() keyCode: $keyCode")
true
}
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
dialog.setOnKeyListener(keyEventListener)
return inflater.inflate(R.layout.fragment_my_dialog, container, false)
}
override fun onDestroyView() {
dialog.setOnKeyListener(null)
super.onDestroyView()
}
companion object {
fun newInstance() = MyDialogFragment()
}
}
A Dialog is shown in/as a separate Window, so your Activity doesn't have the focus for keypresses any more. However, the Dialog has it's own onKeyDown method, so you can make use of that.
Just add a simple DialogInterface.OnKeyListener directly on DialogFragment
Related
I am looking to send a string from FragmentA to FragmentDialog by means of an interface Communicator through my Main Activity (which automatically opens FragmentDialog). Some code to illustrate what I have:
class FragmentA: Fragment() {
private lateinit var communicator: Communicator
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
val view = inflater.inflate(R.layout.fragment_A, container, false)
val title = "My Title"
button.setOnClickListener { communicator.passData(title) }
return view
}
}
class FragmentDialog : DialogFragment() {
var title: String? = ""
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
}
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
val view = inflater.inflate(R.layout.dialog, container, false)
view.button_close.setOnClickListener { dismiss() }
title = arguments?.getString("title")
view.dialog_title.text = title
return view
}
}
interface Communicator {
fun passData (titleInput: String)
}
and in my Main Activity, which extends the interface:
private val fragmentDialog = FragmentDialog()
override fun passData(titleInput: String) {
val bundle = Bundle()
bundle.putString("title", titleInput)
fullScreenDialog.arguments = bundle
val transaction = supportFragmentManager.beginTransaction().add(android.R.id.content, fragmentDialog).addToBackStack(null).commit()
}
When I click the button in FragmentA, I want to send the string title to Communicator, set the XML element with id dialog_title in FragmentDialog and automatically open the fragment. In fact, this works fine. The issue is that my "back button" in FragmentDialog, i.e. view.button_close.setOnClickListener { dismiss() } only works exactly once. If I click button in FragmentA again, FragmentDialog opens fine with the correct title still but button_close no longer dismisses the dialog. What could be causing this? I am not getting any consol errors.
I've tried to invoke DialogFragment from custom view:
DetailsDialogFragment
.newInstance(newSelectedDate, adapterItems[newPosition].progress)
.apply {
show(childFragmentManager, SCORE_DETAILS_DIALOG_TAG)
}
where DetailsDialogFragment looks like this:
class DetailsDialogFragment : AppCompatDialogFragment() {
override fun onCreateDialog(savedInstanceState: Bundle?): Dialog {
return requireActivity().let {
val dialog = Dialog(requireContext(), R.style.CustomDialog)
dialog.window?.setDimAmount(BaseDialogFragment.SCRIM_OPACITY)
dialog.window?.setBackgroundDrawable(ColorDrawable(Color.TRANSPARENT))
dialog
}
}
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
return inflater.inflate(R.layout.fragment_details_dialog, container, false)
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
view.rootView.apply {
findViewById<TextView>(R.id.titleTextView).text = arguments?.getString(ARGS_MONTH)
findViewById<ActionButton>(R.id.button).setOnClickListener {
dismiss()
}
findViewById<ImageView>(R.id.closeImageView).setOnClickListener {
dismiss()
}
}
}
companion object {
fun newInstance(
month: String,
score: Int
): DetailsDialogFragment {
return DetailsDialogFragment()
.apply {
arguments = bundleOf(
ARGS_MONTH to month,
ARGS_SCORE to score
)
}
}
}
}
But I receive the following error:
IllegalStateException: Fragment DetailsDialogFragment has not been attached yet.
at androidx.fragment.app.Fragment.getChildFragmentManager(Fragment.java:980)
...
Is it possible to invoke DialogFragment from custom view at all?
The reason of this exception is that you're trying to use the childFragmentManager of your freshly newly created instance, which is of course not possible since the Dialog fragment hasn't yet has its internals initialized yet (including its childFragmentManager).
If you're using AndroidX I'd use the findFragment extension method inside your custom view and try to do:
Inside your custom view
val dialogFragment = DetailsDialogFragment
.newInstance(newSelectedDate, adapterItems[newPosition].progress)
dialogFragment.show(findFragment().childFragmentManager, SCORE_DETAILS_DIALOG_TAG)
I am getting a does not have a NavController set error inside a OnBackPressedCallback. Here is the code
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
fragmentView = inflater.inflate(R.layout.patient_info_fragment, container, false)
if(Utils.connectedToInternet()){
fragmentView.pastScreeningsButton.visibility = View.GONE
}
requireActivity().onBackPressedDispatcher.addCallback(object : OnBackPressedCallback(true) {
override fun handleOnBackPressed() {
Navigation.findNavController(fragmentView).navigate(R.id.action_patientInfoFragment_to_patientsList)
}
})
setHasOptionsMenu(true)
return fragmentView
}
I am only getting this error when I come back into the fragment where this is implemented.
I have android:name="androidx.navigation.fragment.NavHostFragment" in the home fragment.
To clarify, I am using Navigation controller to do all my Navigation around my app and it works just fine. I only get this error inside this OnBackPressedCallback and only when the user navigates back into the fragment where this is implemented.
Let me know if you need to see any more of my code.
You might run into an issue with leaks of old instances of your fragment. Also it's not a good practice to store the created view within another variable like fragmentView. All in all your onCreateView implementation is doing too many things unrelated to its purpose.
I'd suggest to split up the functionality into relevant life-cycle methods and use the fragment.view directly within your callback. To not run into an issue with unattached views, you then bind and unbind the callback with the life-cycle.
class PatientInfoFragment: Fragment() {
private val callback = object : OnBackPressedCallback(true) {
override fun handleOnBackPressed() {
Navigation.findNavController(view).navigate(R.id.action_patientInfoFragment_to_patientsList)
}
}
override fun onCreate(
savedInstanceState: Bundle?
) {
super.onCreate(savedInstanceState)
setHasOptionsMenu(true)
}
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View = inflater.inflate(R.layout.patient_info_fragment, container, false)
override fun onViewCreated(
view: View,
savedInstanceState: Bundle?
) {
if(Utils.connectedToInternet()){
view.pastScreeningsButton.visibility = View.GONE
}
}
override fun onStart() {
super.onStart()
requireActivity().onBackPressedDispatcher.addCallback(callback)
}
override fun onStop() {
callback.remove()
super.onStop()
}
}
The callback life-cycle binding can be bound with the fragment as lifecycle owner calling the other addCallback(LifecycleOwner, OnBackPressedCallback).
Additionally you could have a look into Android KTX and Kotlin Android Extensions to simplify your implementation.
Move your code in the onViewCreated and pass the view that is provided by the overriden method:
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
requireActivity().onBackPressedDispatcher.addCallback(object : OnBackPressedCallback(true) {
override fun handleOnBackPressed() {
Navigation.findNavController(view).navigate(R.id.action_patientInfoFragment_to_patientsList)
}
})
}
If that also doesn't work, replace the .navigate() with popBastack(R.id.framgment_where_you_want to go, false), in case your previous fragment stays on the backStack
In my application i want use fragment and i want show Toast message just when users see this fragment show message.
I write below codes but when show fragment not show me any Toast!
In java i haven't any issue and show Toast, but when use kotlin not show Toast!
My codes:
class TestFragment : Fragment() {
private val title by lazy { arguments?.getString("title") ?: "" }
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?): View? {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_test, container, false)
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
testFragText.text = title
}
override fun setUserVisibleHint(isVisibleToUser: Boolean) {
super.setUserVisibleHint(isVisibleToUser)
if (isVisibleToUser){Toast.makeText(context, "Show", Toast.LENGTH_SHORT).show()}
}
}
How can i fix it?
Is it possible to create a Navigation Fragment to contain my navigation back button click logic.
Multiple Fragment's that have a back button would then be able then inherit from the Navigation Fragment.
I'm new to Kotlin development. As you see below the SigninFragment inflates the view, I'm not sure how to get a reference to the view & back button in a parent Navigation Fragment
class SigninFragment : Fragment() {
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
val view = inflater.inflate(R.layout.fragment_signin, container, false)
// Navigation back button logic
var headerBackButton = view.findViewById<ImageButton>(R.id.headerBackButton)
headerBackButton.setOnClickListener {
val navController = NavHostFragment.findNavController(this#SignInFragment)
navController.navigateUp()
}
return view
}
}
I'm not sure if I got your problem right but could this be the trick?
open class NavigationFragment() : Fragment() {
fun asignNavigationBackClickListener(backButton: View) {
backButton.setOnClickListener {
val navController = NavHostFragment.findNavController(this#NavigationFragment)
navController.navigateUp()
}
}
}
class SigninFragment : NavigationFragment() {
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
val view = inflater.inflate(R.layout.fragment_signin, container, false)
asignNavigationBackClickListener(view.findViewById(R.id.headerBackButton))
return view
}
}
I think you can use this code for going back to the previous activity:
headerBackButton.setOnClickListener {
finish()
}