如何在其他片段中更新ListView?
public class ChooseCS extends FragmentActivity {
final private Context context = this;
private HashMap<String, List<String>> mCitiesStreets = null;
private View rootViewStreetChangeFragment = null;
private SimpleAdapter adapter;
...
private static final int NUM_PAGES = 3;
private ViewPager mPager;
private PagerAdapter mPagerAdapter;
...
和两个片段
public class CityChangeFragment extends Fragment {
和
public class StreetChangeFragment extends Fragment {
...
mMapDataAdapter.put("streets", fillcities);
adapter = new SimpleAdapter(
rootViewStreetChangeFragment.getContext(),
mMapDataAdapter.get("streets"), R.layout.grid_streets_4_7,
from, to);
mDataListViewStreets.setAdapter(adapter);
...
我需要从CityChangeFragment在StreetChangeFragment中更新ListView,我在那里更改数据
答案 0 :(得分:1)
您可以使用LocalBroadcastManager来实现此目的。
在你的StreetChangeFragment中写下代码
@Override
public void onCreate(Bundle savedInstanceState) {
...
// Register to receive messages.
// We are registering an observer (mMessageReceiver) to receive Intents
// with actions named "custom-event-name".
LocalBroadcastManager.getInstance(this).registerReceiver(mMessageReceiver,
new IntentFilter("custom-event-name"));
}
// Our handler for received Intents. This will be called whenever an Intent
// with an action named "custom-event-name" is broadcasted.
private BroadcastReceiver mMessageReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
// Get extra data included in the Intent
String message = intent.getStringExtra("message");
Log.d("receiver", "Got message: " + message);
}
};
@Override
protected void onDestroy() {
// Unregister since the activity is about to be closed.
LocalBroadcastManager.getInstance(this).unregisterReceiver(mMessageReceiver);
super.onDestroy();
}
使用以下方法从CityChangeFragment向StreetChangeFragment发送广播消息
private void sendMessage() {
Log.d("sender", "Broadcasting message");
Intent intent = new Intent("custom-event-name");
// You can also include some extra data.
intent.putExtra("message", "This is my message!");
LocalBroadcastManager.getInstance(this).sendBroadcast(intent);
}
注意:您可以使用intent传递数据(此处您也可以在listview中更新数据)
您可以查看以下链接,了解有关LocalBroadcastManager的更多信息
https://developer.android.com/reference/android/support/v4/content/LocalBroadcastManager.html
答案 1 :(得分:0)
接口是个好主意,这个想法基本上是定义一个接口,让活动实现该接口。
一旦实现了该接口,您就可以在它覆盖的方法中执行任何操作。 Simple Developer Blog有一个很好的教程如何做到这一点。
你需要在片段中声明一个方法,它可以通过从适配器获取片段实例来从活动中执行,如
Fragment fragment= mPagerAdapter.getItem(int positon);
((StreetChangeFragment )).updateList();
在StreetChangeFragment声明方法中并执行您想要的其他操作,谢谢