Vishak A Kamath
Vishak A Kamath

Reputation: 137

How do I send a message from One fragment to another on a Click of the button from the First one?

I have tried this code but clicking a button in First Fragment isn't changing the string value in the Second.

This is the kotlin file of First Fragment. It has two buttons on click of which should change the string value. I have also created an inner interface inside this class which is OnButtonClickListener, as mentioned in Android Documentation.

viewHolder = inflater.inflate(R.layout.fragment_test_one, container, false)

    viewHolder.btnFragTestOneMessageOne.setOnClickListener {
        listener.onButtonCLickListener("MESSAGE ONE")
    }

    viewHolder.btnFragTestOneMessageTwo.setOnClickListener {
        listener.onButtonCLickListener("MESSAGE TWO")
    }

    return viewHolder

This is the second fragment. This fragment's layout also has a textView which has to be changed on the click of a button inside the First fragment.

lateinit var viewHolder: View

override fun onCreateView(
    inflater: LayoutInflater, container: ViewGroup?,
    savedInstanceState: Bundle?
): View? {
    viewHolder = inflater.inflate(R.layout.fragment_test_two, container, false)
    return viewHolder
}

And here is the activity file.

override fun onButtonCLickListener(strMessage: String) {
    testTwoFragment.viewHolder.tvFragTestTwo.text = strMessage
}


override fun onCreate(savedInstanceState: Bundle?) {

    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_fragment_test)

    supportFragmentManager.beginTransaction().add(R.id.flFragTest, TestOneFragment()).commit()

    btnTestFragOne.setOnClickListener {
        supportFragmentManager.beginTransaction().replace(R.id.flFragTest, testOneFragment).commit()
    }


    btnTestFragTwo.setOnClickListener {
        supportFragmentManager.beginTransaction().replace(R.id.flFragTest, testTwoFragment).commit()
    }

}

Upvotes: 1

Views: 600

Answers (1)

Ashish
Ashish

Reputation: 6919

Change your message in String format then

Use Bundle to send String:

//Put the value
YourNewFragment ldf = new YourNewFragment ();
Bundle args = new Bundle();
args.putString("YourKey", "YourValue");
ldf.setArguments(args);

//Inflate the fragment
getFragmentManager().beginTransaction().add(R.id.container, ldf).commit();

In onCreateView of the new Fragment:

//Retrieve the value
String value = getArguments().getString("YourKey");

Upvotes: 1

Related Questions