buy buy
buy buy

Reputation: 1

How to refresh the data after click the item on listview for fragment

I have two fragments both AFragment and BFragment. The AFragment has a ListView. The BFragment has a Texview and a Button. The Afragment will change the fragment and putString to BFragment when the user clicked the item on ListView. The BFragment got the data from Afragment and display the date to TextView. How can I do?

The sample is like that

enter image description here

Upvotes: 0

Views: 127

Answers (3)

Zain
Zain

Reputation: 40840

You can do this by below approach without using external libraries:

Assume you've a MainActivity which hosts the two fragments FragmetA (which has a ListView) and FragmentB (which has the TextView)

Here's the full scenario:

  1. Create an interface @ FragmentB which will be used by MainActivity to know when a list item is selected
  2. MainActivity will register a listener to FragmentA by overriding onAttachFramemnt() and implementing this interface
  3. When the user selects a list item from FragmentA; FragmentB will trigger the callback back to MainActivity
  4. MainActivity will forward the trigger to a public method in FragmentB which is used to set the text of the TextView to the current item.

Here is the code:

1. Layout

1.1 activity_main

<?xml version="1.0" encoding="utf-8"?>
<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"
    tools:context=".MainActivity">

    <fragment
        android:id="@+id/fragment_b"
        android:name="com.example.android.sendingdatafromfragmenta_to_fragmentb.FragmentB"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />

    <fragment
        android:id="@+id/fragment_a"
        android:name="com.example.android.sendingdatafromfragmenta_to_fragmentb.FragmentA"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />

</LinearLayout>

1.2 fragment_a

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <ListView
        android:id="@+id/listView"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />

</LinearLayout>

1.3 fragment_b

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <TextView
        android:id="@+id/tvSelectedItem"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="No Item selected" />

</LinearLayout>

2. Java

2.1 MainActivity

public class MainActivity extends AppCompatActivity implements FragmentA.OnListItemClickListener {

    private static final String LOG_TAG = "LOG_TAG";
    private FragmentB mFragmentB;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        // inflating fragment B from xml
        mFragmentB = (FragmentB) getSupportFragmentManager().findFragmentById(R.id.fragment_b);

    }


    @Override
    public void onAttachFragment(Fragment fragment) {
        Log.i(LOG_TAG, "onAttachFragment");
        super.onAttachFragment(fragment);
        if (fragment instanceof FragmentA) {
            ((FragmentA) fragment).setOnListItemClickListener(this);
        }

    }

    @Override
    public void onListItemClick(String selectedITem) {
        mFragmentB.setSelectedITemText(selectedITem);
    }
}

2.2 FragmentA

public class FragmentA extends Fragment {

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {

        View view = inflater.inflate(R.layout.fragment_a, container, false);

        final String[] data = {"item 1", "item 2", "item 3", "item 4", "item 5"};

        ListView listView = view.findViewById(R.id.listView);

        ArrayAdapter adapter = new ArrayAdapter(requireContext(), android.R.layout.simple_list_item_1, data);

        listView.setAdapter(adapter);

        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                if (mOnListItemClickListener != null) {
                    mOnListItemClickListener.onListItemClick(data[position]);
                }
            }
        });

        return view;
    }

    interface OnListItemClickListener {
        void onListItemClick(String selectedITem);
    }

    OnListItemClickListener mOnListItemClickListener;

    public void setOnListItemClickListener(OnListItemClickListener listener) {
        mOnListItemClickListener = listener;
    }
}

2.3 FragmentB

public class FragmentB extends Fragment {

    View view;

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        view = inflater.inflate(R.layout.fragment_b, container, false);
        return view;
    }

    public void setSelectedITemText(String text) {
        TextView selectedItemTextView = view.findViewById(R.id.tvSelectedItem);
        selectedItemTextView.setText(text);
    }
}

Results

enter image description here

enter image description here

Upvotes: 0

Bhavik Parmar
Bhavik Parmar

Reputation: 54

You can use Interface and LocalBroadcastReceiver both for refreshing the Fragment. Create one LocalBroadcastReceiver

LocalBroadcastManager.getInstance(context).registerReceiver(refreshFragment ,
            new IntentFilter("refreshFragment"));

and its Method in BFragment

private BroadcastReceiver refreshFragment = new BroadcastReceiver() {
    @Override
    public void onReceive(Context context, Intent intent) {

        // Do The Changes You Want To Refresh BFragment

    }
};

And Than Call This LocalBroadcastReceiver in OnClick Event of the Button in AFragment.

    Intent intent =new Intent("refreshFragment");

    LocalBroadcastManager.getInstance(context).sendBroadcast(intent);

Upvotes: 0

Nguyễn Trung Hiếu
Nguyễn Trung Hiếu

Reputation: 2032

You can use libs https://github.com/greenrobot/EventBus . very easy!!!

EventBus in 3 steps

Define events:

 public static class MessageEvent { /* Additional fields if needed */ }

Prepare subscribers: Declare and annotate your subscribing method, optionally specify a thread mode:

@Subscribe(threadMode = ThreadMode.MAIN)  
public void onMessageEvent(MessageEvent event) {/* Do something */};

Register and unregister your subscriber. For example on Android, activities and fragments should usually register according to their life cycle:

 @Override
 public void onStart() {
 super.onStart();
 EventBus.getDefault().register(this);
 }

 @Override
 public void onStop() {
 super.onStop();
 EventBus.getDefault().unregister(this);
 }

Post events:

 EventBus.getDefault().post(new MessageEvent());

Upvotes: 1

Related Questions