问题描述
我有 2个活动:活动1(MainActivity)和活动2.
I have 2 activities: Activity1 (MainActivity) and Activity2.
Activity1具有3个片段:片段_1,片段_2和片段_3.
Activity1 has 3 Fragments: Fragment_1, Fragment_2 and Fragment_3.
我想根据对Activity2执行的操作来更改Fragment_3的数据.
I want to change data of Fragment_3 according to action performed on Activity2.
我的问题是,我从Fragment_2调用Activity2并在其中执行某些操作(在Activity2中),然后回到Fragment_2和View Fragmnet_3,Fragment_3的数据没有变化(Fragment_3的数据应根据执行的操作进行更改活动2).
My problem is that, I call Activity2 from Fragment_2 and do something there (in Activity2) and hit back to Fragment_2 and View Fragmnet_3, there are no change in data of Fragment_3 (Fragment_3' data should be changed according to action performed on Activity2).
但是,当我选择Fragment_1,然后选择Fragment_3时,其数据会根据对Activity_2的操作进行更改.
But when I choose Fragment_1 and then choose Fragment_3, data of it is changed according to action on Activity_2.
我希望我从Fragment_2调用Activity2并在那里执行一些操作(在Activity2中),然后回到Fragment_2和View Fragmnet_3,数据将发生变化.
I want I call Activity2 from Fragment_2 and do something there (in Activity2) and hit back to Fragment_2 and View Fragmnet_3, data will change.
该怎么做?
推荐答案
我做到了!使用BroadCastRecevier!
i made it! Use BroadCastRecevier!
frament3:
public class MyFragment3 extends Fragment {
String key;
private TextView tv;
@Override
public void onResume() {
//register LocalBroadCastReceiver
LocalBroadcastManager lm = LocalBroadcastManager.getInstance(getContext());
MyReceiver receiver = new MyReceiver();
IntentFilter filter = new IntentFilter();
filter.addAction("com.action.sodemo");
lm.registerReceiver(receiver,filter);
super.onResume();
}
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_item3,container,false);
tv = (TextView) view.findViewById(R.id.tv_3);
return view;
}
class MyReceiver extends BroadcastReceiver{
@Override
public void onReceive(Context context, Intent intent) {
key = intent.getStringExtra("value");
tv.setText(key);
}
}
}
活动2:
public class Activity_2 extends AppCompatActivity {
private LocalBroadcastManager lm;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_activity_2);
lm=LocalBroadcastManager.getInstance(this);
Button btn = (Button) findViewById(R.id.btn_choose);
btn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//send value to fragment3
Intent intent = new Intent("com.action.sodemo");
intent.putExtra("value","change");
lm.sendBroadcast(intent);
}
});
}
}
这篇关于数据不会自动在ViewPager的Fragment中重新加载的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!