Last active
March 16, 2021 14:31
-
-
Save esabook/b6533c4f84d136a79eccc18248275bfa to your computer and use it in GitHub Desktop.
[Android] Single Fragment for multiple layout/*.xml in <navigation>
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package * | |
import android.os.Bundle | |
import android.view.LayoutInflater | |
import android.view.View | |
import android.view.ViewGroup | |
import androidx.fragment.app.Fragment | |
class LayoutFragment : Fragment() { | |
override fun onCreateView( | |
inflater: LayoutInflater, | |
container: ViewGroup?, | |
savedInstanceState: Bundle? | |
): View? { | |
val layout = getString(R.string.base_fragment_layout) | |
arguments?.getInt(layout)?.let { | |
return inflater.inflate(it, container, false) | |
} | |
return null | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package * | |
import android.os.Bundle | |
import androidx.fragment.app.Fragment | |
import android.view.LayoutInflater | |
import android.view.View | |
import android.view.ViewGroup | |
import android.widget.Button | |
import androidx.appcompat.widget.LinearLayoutCompat | |
import androidx.navigation.fragment.FragmentNavigator | |
import androidx.navigation.fragment.findNavController | |
/** | |
* A simple [Fragment] subclass as the default destination in the navigation. | |
*/ | |
class MainFragment : Fragment(R.layout.fragment_first) { | |
override fun onViewCreated(view: View, savedInstanceState: Bundle?) { | |
super.onViewCreated(view, savedInstanceState) | |
val viewGroup = view.findViewById<LinearLayoutCompat>(R.id.vg_content) | |
viewGroup?.run { | |
findNavController().graph.forEach graph@{ d -> | |
if ((d as FragmentNavigator.Destination).className == MainFragment::class.java.name) return@graph | |
val button = Button(requireContext()) | |
button.text = d.label | |
button.setOnClickListener { findNavController().navigate(d.id) } | |
this.addView(button) | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment