我有一个片段,其中包含一些项目的列表视图。单击列表视图中的项目时,将启动“活动”以查看有关列表视图的详细信息。 Activity上有一个后退按钮,它将我们带回到片段页面。按下后退按钮并关闭活动页面后,我希望在片段列表视图中刷新数据。我尝试过onResume()方法,但它不刷新数据。
有人可以帮助我如何实现这一目标。
public class FavCommittee extends Fragment {
public ArrayList<Committee> favCommitteeData = new ArrayList<>();
@Nullable
@Override
public void onResume(){
super.onResume();
final SharedPreferences pref = getContext().getSharedPreferences("MyFav", 0);
final SharedPreferences.Editor editor = pref.edit();
View rootView =getView();
Map<String,?> entries = pref.getAll();
final Set<String> keys = entries.keySet();
int count=0;
for (String key:keys) {
String val = pref.getString(key, null);
String[] store = val.split(":");
if (store[0].equals("committee"))
count=count+1;
}
for (int i=0;i<keys.size();i++) {
String val = pref.getString(Integer.toString(i), null);
if (val != null) {
String[] store = val.split(":");
if (store[0].equals("committee")) {
count = count - 1;
new GetAllCommittees(getContext(), rootView).execute(store[1], Integer.toString(count));
}
}
} final ListView yourListView = (ListView) rootView.findViewById(R.id.house_listview);
yourListView.setOnItemClickListener(new android.widget.AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view,int position, long id) {
Committee obj = (Committee)yourListView.getItemAtPosition(position);
Intent intent = new Intent(FavCommittee.this.getActivity(), committee_info.class);
intent.putExtra("Committee",obj.getCommittee_id());
startActivity(intent);
}
});
}
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.house, container, false);
return rootView;
}
答案 0 :(得分:0)
当你在Fragments之间转换时,调用addToBackStack()作为FragmentTransaction的一部分:
FragmentTransaction tx = fragmentManager.beginTransation();
tx.replace( R.id.fragment, new MyFragment() ).addToBackStack( "tag").commit();
如果您需要更详细的控制(即当某些片段可见时,您想要取消后退键),您可以在片段的父视图上设置OnKeyListener:
//您需要添加以下行才能使此解决方案正常工作
fragment.getView().setFocusableInTouchMode(true);
fragment.getView().requestFocus();
fragment.getView().setOnKeyListener( new OnKeyListener()
{
@Override
public boolean onKey( View v, int keyCode, KeyEvent event )
{
if( keyCode == KeyEvent.KEYCODE_BACK )
{
return true;
}
return false;
}
} );
答案 1 :(得分:0)
getSupportFragmentManager()。beginTransaction()。add(R.id.fragContainer,new FavCommittee(),FavCommittee .class.getName())。commit();
试试这段代码。 将代码放在您在活动中添加片段的位置