I made swipe PageView with fragment like that http://www.androidhive.info/2013/10/android-tab-layout-with-swipeable-views-1/
Fragment2 have function myUpdate()
which updates some data in Fragment2 (data from sql to list). I could call it easely in Fragment2, but I also need to run myUpdate()
from Fragment1 or from other Activity and i don't know how.
I found a few ways but then need R.id.* or tag and i have no idea where to find it.
FragmentManager fm = getFragmentManager();
Fragment2 fragment = (Fragment2) fm.findFragmentByTag(<...>);
fragment.myUpdate();
or same with findViewById
... I suppose I should make some changes in xml, but i don't know what to change... Thanks.
There are multiple ways to achieve this, one would be local broadcasts. Implementing a BroadcastReceiver
for local broadcasts is exactly the same as for normal broadcasts:
private BroadcastReceiver receiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if(action != null && action.equals("update")) {
// perform your update
}
}
};
You can register a BroadcastReceiver
for your local broadcasts in the first Fragment
like this:
LocalBroadcastManager broadcastManager = LocalBroadcastManager.getInstance(context);
IntentFilter intentFilter = new IntentFilter("update");
// Here you can add additional actions which then would be received by the BroadcastReceiver
broadcastManager.registerReceiver(receiver, intentFilter);
and you can send local broadcasts like this:
Intent intent = new Intent("update");
LocalBroadcastManager broadcastManager = LocalBroadcastManager.getInstance(context);
broadcastManager.sendBroadcast(intent);
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments