Its easy to link texts on MainActivity.kt file but I can't figure out how to link the same on a Fragment.kt file cause the functions are different.
This is the code for MainActivity.kt
class MainActivity : AppCompatActivity() {
var text: TextView? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
text = findViewById(R.id.textLink)
text?.setOnClickListener({
var click = Intent (this#MainActivity, LinkText:: class.java)
startActivity(click)
})
}
}
I want to link the text in HomeFragment.kt which looks like this
class HomeFragment : Fragment() {
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
return inflater.inflate(R.layout.fragment_home, null)
}
}
I need the code for the same.
Suppose that in fragment_home.xml you have a TextView with id textLink. Here is code how to "link" text on the HomeFragment.
class HomeFragment : Fragment() {
var text: TextView? = null
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
val view = inflater.inflate(R.layout.fragment_home, container, false)
text = view.findViewById(R.id.textLink)
text?.setOnClickListener {
var click = Intent(requireActivity(), LinkText::class.java)
startActivity(click)
}
return view
}
}
Related
Here is my code:-
class ACFragment : Fragment() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
}
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
val id = "ac"
fb_ac.setOnClickListener {
val intent = Intent(this#ACFragment, AddFunction::class.java)
intent.putExtra("id", id)
startActivity(intent)
}
return inflater.inflate(R.layout.fragment_ac, container, false)
}
}
I want to transfer data from fragment to activity using Intent but I am unable to do it. Can Someone please help me?
You can retrieve the id string in the AddFunction activity by calling the getStringExtra method:
override fun onCreate(savedInstanceState: Bundle) {
...
val id = intent.getStringExtra("id") ?: ""
}
Also, you should change your onCreateView declaration like this:
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
val view = inflater.inflate(R.layout.fragment_ac, container, false)
val id = "ac"
view.findViewById<Button>(R.id.fb_ac).setOnClickListener {
val intent = Intent(requireContext(), AddFunction::class.java)
intent.putExtra("id", id)
startActivity(intent)
}
return view
}
Im trying to pass data between two fragments but i have an error with arguments in execution when i launch fullFragment
i updated my code
Can you help me ?
architecture :
ListeFragment (sender) :
class ListeFragment : Fragment() {
companion object {
fun newInstance(s: String) = ListeFragment()
}
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View {
val layout = inflater.inflate(R.layout.liste_fragment, container, false)
val photo1 = layout.findViewById<ImageView>(R.id.imageButton1)
val model = ViewModelProviders.of(this).get(ListeViewModel::class.java)
imageButton1.setOnClickListener {
val newFragment = FullFragment()
val args = Bundle()
args.putString("key1", "data")
newFragment.arguments = args
Navigation.findNavController(imageButton1).navigate(R.id.versFullFragment);
}
FullFragment (receiver):
class FullFragment : Fragment() {
companion object {
fun newInstance() = FullFragment()
}
private lateinit var viewModel: FullViewModel
override fun onCreate( savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
var value1 = getArguments()?.getString("key1")
Log.v("value" , value1.toString())
Toast.makeText(context, value1.toString(), Toast.LENGTH_SHORT).show()
}
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
val layout = inflater.inflate(R.layout.full_fragment, container, false)
return layout
}
I don't know what "newFragment.arguments = args" do because in FullFragment class I don't see any variable with that name, however you have to use "Fragment.setArguments(Bundle)" to set Fragment Arguments from the first one. Then in the Full you will have a correct result from "FullFragment.getArguments()" method.
PS: don't forget that the Context could be NULL in Fragment class and it should be handled in proper way.
I'm new to Kotlin and android development but i can't find why my program isn't working.
I'm trying to be able to communicate from my first fragment to his child, and testing it with a string but it won't display.
Thanks in advance for your help !!!
My first fragment :
class FirstFragment : Fragment() {
private lateinit var viewModel : Communicator
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_first, container, false)
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
viewModel = activity?.run {
ViewModelProvider(this).get(Communicator::class.java) // .of supprimé
} ?: throw Exception("Invalid Activity")
viewModel.message.value = "test"
view.findViewById<Button>(R.id.button_stall_selection).setOnClickListener {
findNavController().navigate(R.id.action_FirstFragment_to_SecondFragment)
}
}
}
Here is my second :
class SecondFragment() : Fragment() {
private lateinit var viewModel :Communicator
private var msg: String? = ""
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_second, container, false)
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
viewModel = activity?.run {
ViewModelProvider(this).get(Communicator::class.java) // .of deleted
} ?: throw Exception("Invalid Activity")
viewModel.message.observe(viewLifecycleOwner, Observer {
msg = viewModel.message.value
})
view.findViewById<TextView>(R.id.textView_1).text = msg
view.findViewById<Button>(R.id.button_second).setOnClickListener {
findNavController().navigate(R.id.action_SecondFragment_to_FirstFragment)
}
}
}
and finally here is the viewModel class i'm trying to use in order to communicate :
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
class Communicator() : ViewModel(){
val message =MutableLiveData<String>()
fun setMsgCommunicator(msg:String){
message.setValue(msg)
}
}
In your FirstFragment, try to call viewModel.setMsgCommunicator("test") instead of directly calling viewModel.message.value = "test"
I have a simply Activity. In this activity I want start a fragment. But the Fragment doesn't start.
This is my Activity
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
//start Homefragment
startHomeFragment()
}
/**
* Create Homefragment
*/
private fun startHomeFragment() {
val homeFragment = fragmentManager.findFragmentByTag(statics.TAG) ?: HomeFragment()
fragmentManager.beginTransaction()
.replace(R.id.container, homeFragment, statics.TAG)
.commit()
}
And this is my Fragment
class HomeFragment : Fragment() {
object statics {
#JvmField val TAG = "Homefragment"
}
override fun onCreateView(inflater: LayoutInflater?, container: ViewGroup?, savedInstanceState: Bundle?): View? {
return super.onCreateView(inflater, container, savedInstanceState)
inflater?.inflate(R.layout.fragment_home, container)
background_home.setBackgroundResource(R.drawable.gc_bg_home)
All the code after
return super.onCreateView(inflater, container, savedInstanceState)
is unreachable. Just read IDE warnings.
Also, layout becomes attached only if you returned it from onCreateView, i. e. return inflater.inflate(...).
In Kotlin the onCreateView should be on this way
override fun onCreateView(inflater: LayoutInflater?, container: ViewGroup?,
savedInstanceState: Bundle?): View? {
return inflater!!.inflate(R.layout.input_field_frag, container, false)
}
If you want to add somthing inside you fragment you can use onViewCreated method and do whatever you want here
override fun onViewCreated(view: View?, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
//Here u can call function of add listners to button...
})
}
Like this you gonna create a safe propriate code
Solved:
class HomeFragment : Fragment() {
object statics {
#JvmField val TAG = "Homefragment"
}
override fun onCreateView(inflater: LayoutInflater?, container: ViewGroup?, savedInstanceState: Bundle?): View? {
Toast.makeText(activity, "HomeFragment", Toast.LENGTH_SHORT).show()
return inflater?.inflate(R.layout.fragment_home, container, false)
}
}
class HomeFragment : Fragment() {
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?): View? {
// Inflate the layout for this fragment
val v = inflater.inflate(R.layout.fragment_home, container, false)
val fab = v.findViewById(R.id.fab) as FloatingActionButton
fab.setOnClickListener {
val blankFragment = BlankFragment()
val manager = childFragmentManager
manager.beginTransaction().replace(R.id.frame_container, blankFragment, blankFragment.tag).commit()
// System.out.println("You have reached the floating action button")
}
return v
}
}
Getting a no view found error. I may have issues with the R.id.frame_content but Kotlin doesn't immediately identify all id values...
This may not be the best way and I apologize for the horrible formatting I does this while answer out on my phone and it's hard to get it perfect. Anyways In the activity that holds your fragments, such as MainActivity.kt add...
supportFragmentManager.beginTransaction.add(R.id.fragment_home, HomeFragment.newInstance, "HomeFragment").commit()
In your HomeFragment.kt change the following.
class HomeFragment: Fragment(){
companion object {
fun newInstance(): HomeFragment{
return HomeFragment() }
fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
val view: View = inflater!!.inflate(R.layout.fragment_home, container, false)
val activity = activity
return view
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
val clickListener = View.OnClickListener { view ->
when (view.getId()) {
R.id.fab -> NextFragment()
}
}
fab.setOnClickListener(clickListener)
}
NextFragment(){
val fragManager = activity?.supportFragmentManager
fragManager?.beginTransaction()?.replace(R.id.frame_container, BlankFragment.newInstance(), "blankFragment")?.commit()
}
Make sure you make the same changes to BlankFragment.kt
class BlankFragment: Fragment(){
companion object {
fun newInstance(): BlankFragment{
return BlankFragment() }
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
val view: View = inflater!!.inflate(R.layout.fragment_blank, container, false)
val activity = activity
return view
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
//Do some stuff with your views in BlankFragment here
}
}