Android< communication between Fragments and communication between Fragments and Activities >

Keywords: Android Attribute Fragment xml

1. Situational assumptions:

Suppose there is a requirement, a layout with FragmentLeft and FragmentRight in an Activity, and a layout with Textview at the bottom.

Now when a button in FragmentLeft is clicked, FragmentRight and Textview in Activeness respond, similar to this effect:

2. Solutions:

i. Define an interface in FragmentLeft:

 public interface ButtonClick {
        void sendTextToActivityAndFragmentRight(String data);
    }

ii. Then implement this interface in Activity

In the implemented interface, you can write down the actions you want to do, such as updating the UI of Activity, and passing

FragmentRight fragmentRight= (FragmentRight) getSupportFragmentManager().findFragmentById(R.id.fragment2);
        fragmentRight.updateText(data);

This updateText method is implemented in your FragmentRight
iii. Declare a reference to an interface in FragmentLeft, and then obtain an instance of the interface in Onattach(Context context) in FragmentLeft

 @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        try {
            mlistener = (ButtonClick) getActivity();
        } catch (ClassCastException e) {
            throw new ClassCastException(getActivity().toString()
                    + " must implement ButtonClicked");
        }
    }

3. Complete code:
FragmentLeft:

package com.example.geekp.fragmentcommunication;


import android.content.Context;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;


public class FragmentLeft extends Fragment implements View.OnClickListener {
    private ButtonClick mlistener;
    private Button button1;
    private Button button2;
    private Button button3;
    private Button button4;
    private Button button5;


    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.button1:
                mlistener.sendTextToActivityAndFragmentRight("The button was clicked.");
                break;
            case R.id.button2:
                mlistener.sendTextToActivityAndFragmentRight("Button 2 was clicked");
                break;
            case R.id.button3:
                mlistener.sendTextToActivityAndFragmentRight("Button 3 was clicked");
                break;
            case R.id.button4:
                mlistener.sendTextToActivityAndFragmentRight("Button 4 was clicked");
                break;
            case R.id.button5:
                mlistener.sendTextToActivityAndFragmentRight("Button 5 was clicked");
                break;
            default:
                break;
        }
    }

    public interface ButtonClick {
        void sendTextToActivityAndFragmentRight(String data);
    }


    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        try {
            mlistener = (ButtonClick) getActivity();
        } catch (ClassCastException e) {
            throw new ClassCastException(getActivity().toString()
                    + " must implement ButtonClicked");
        }
    }

    @Override
    public void onDetach() {
        super.onDetach();
        mlistener = null;//Avoiding memory leaks
        super.onDetach();
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_fragment_left, container, false);
        button1 = (Button) view.findViewById(R.id.button1);
        button2 = (Button) view.findViewById(R.id.button2);
        button3 = (Button) view.findViewById(R.id.button3);
        button4 = (Button) view.findViewById(R.id.button4);
        button5 = (Button) view.findViewById(R.id.button5);
        //Setting up listening events
        button1.setOnClickListener(this);
        button2.setOnClickListener(this);
        button3.setOnClickListener(this);
        button4.setOnClickListener(this);
        button5.setOnClickListener(this);
        // Inflate the layout for this fragment
        return view;
    }


}

fragment_left.xml:

<LinearLayout 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"
    android:orientation="vertical"
    android:background="@color/colorPrimary"
    tools:context="com.example.geekp.fragmentcommunication.FragmentLeft">

    <!-- TODO: Update blank fragment layout -->
    <Button
        android:layout_marginTop="40dp"
        android:id="@+id/button1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Button 1" />

    <Button
        android:id="@+id/button2"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Button two" />

    <Button
        android:id="@+id/button3"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Button three" />

    <Button
        android:id="@+id/button4"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Button four" />

    <Button
        android:id="@+id/button5"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Button five" />
</LinearLayout>

FragmentRight:

package com.example.geekp.fragmentcommunication;


import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;


/**
 * A simple {@link Fragment} subclass.
 */
public class FragmentRight extends Fragment {
    private  TextView textView;

    public FragmentRight() {
        // Required empty public constructor
    }


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view=inflater.inflate(R.layout.fragment_fragment_right, container, false);
        textView= (TextView) view.findViewById(R.id.textview);
        // Inflate the layout for this fragment
        return view;
    }

    public void updateText(String text) {
    textView.setText(text);
    }
}

fragment_right.xml:

<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"
    android:background="@color/colorAccent"
    tools:context="com.example.geekp.fragmentcommunication.FragmentRight">

    <!-- TODO: Update blank fragment layout -->
    <TextView
        android:id="@+id/textview"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:text="content" />

</FrameLayout>

MainActivity:

package com.example.geekp.fragmentcommunication;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity implements FragmentLeft.ButtonClick{
    private TextView textView;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        textView= (TextView) findViewById(R.id.textviewinactivity);
    }

    @Override
    public void sendTextToActivityAndFragmentRight(String data) {
        FragmentRight fragmentRight= (FragmentRight) getSupportFragmentManager().findFragmentById(R.id.fragment2);
        fragmentRight.updateText(data);
        textView.setText(data);
    }
}

activity_main.xml:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/activity_main"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="com.example.geekp.fragmentcommunication.MainActivity">

    <fragment
        android:layout_width="100dp"
        android:layout_height="400dp"
        android:name="com.example.geekp.fragmentcommunication.FragmentLeft"
        android:layout_alignParentTop="true"
        android:layout_alignParentStart="true"
        android:id="@+id/fragment1" />

    <fragment
        android:layout_width="250dp"
        android:layout_height="400dp"
        android:name="com.example.geekp.fragmentcommunication.FragmentRight"
        android:layout_alignParentTop="true"
        android:layout_alignParentEnd="true"
        android:id="@+id/fragment2" />

    <TextView
        android:id="@+id/textviewinactivity"
        android:layout_marginTop="10dp"
        android:background="@color/colorAccent"
        android:layout_width="match_parent"
        android:layout_height="200dp"
        android:layout_alignParentStart="true"
        android:layout_below="@+id/fragment1" />
</RelativeLayout>

Posted by deezin on Wed, 13 Feb 2019 16:45:18 -0800