好吧,考虑到我有两个片段。FragmentTab1 & ShowAllContactFragment. FragmentTab1 包括 列表视图 &和a 扣子. 当按钮被点击时,我在我的viewpager中替换ShowAllContactFragment。当显示 ShowAllContactFragment在列表视图中,用户可以通过选择复选框来选择多个联系人,同时它还具有一个 "联系人 "功能。ADD 联系按钮。
我需要的是: 我想在FragmentTab1中更新现有的列表视图,当用户按下 ADD ShowAllContactFragment中的按钮,在这个列表视图中选择一些联系人后。我也删除了ShowAllContactFragment,并显示FragmentTab1时,会出现这种情况。
我的解决状态: 我遵循的是 安卓开发者 论坛,通过Activity进行碎片之间的数据沟通。我几乎完成了。我在ShowAllContactFragment &中创建了OnContactSelectedListener接口;在MainActivity中实现。一切都很好!。调试之后,我检查了我的回调方法,发现我的数据在 主要活动 但我不能替换ShowAllContactFragment &;不能显示之前的FragmentTab1 &;更新它的列表视图。
为了从FragmentTab1打开ShowAllContactFragment,我写了这样的内容。
ShowAllContactFragment allContactsFragment = new ShowAllContactFragment();
FragmentTransaction transaction = getFragmentManager()
.beginTransaction();
transaction.addToBackStack(null);
transaction.add(R.id.fragmentTabLayout1, allContactsFragment);
transaction.commit();
My MainActivity & FragmentAdapter Looks :
public class MainActivity extends SherlockFragmentActivity implements
ShowAllContactFragment.OnContactSelectedListener {
ActionBar.Tab Tab1, Tab2, Tab3, Tab4;
private Context context = this;
// view pager
// Declare Variables
ActionBar actionBar;
ViewPager mPager;
Tab tab;
FragmentAdapter mAdapter;
List<Fragment> fragmentList = new ArrayList<Fragment>();
ArrayList<Person> blackListPersonList;
private final static String TAG_FRAGMENT = "TAG_FRAGMENT";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// set application in portrait mode
ActivityHelper.initialize(this);
actionBar = getSupportActionBar();
actionBar.setDisplayShowHomeEnabled(true);
actionBar.setDisplayShowTitleEnabled(true);
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
addFragmentsInList();
// Locate ViewPager in activity_main.xml
mPager = (ViewPager) findViewById(R.id.pager);
// add an adapter to pager
mAdapter = new FragmentAdapter(getSupportFragmentManager(), mPager,
actionBar, fragmentList);
mPager.setAdapter(mAdapter);
addActionBarTabs();
}
public void addFragmentsInList() {
FragmentTab1 aFragmentTab1 = new FragmentTab1();
fragmentList.add(new FragmentTab1());
fragmentList.add(new FragmentTab2());
fragmentList.add(new FragmentTab3());
}
private void addActionBarTabs() {
String[] tabs = { "Tab 1", "Tab 2", "Tab 3" };
for (String tabTitle : tabs) {
ActionBar.Tab tab = actionBar.newTab().setText(tabTitle)
.setTabListener(tabListener);
actionBar.addTab(tab);
}
}
private ActionBar.TabListener tabListener = new ActionBar.TabListener() {
@Override
public void onTabSelected(ActionBar.Tab tab, FragmentTransaction ft) {
mPager.setCurrentItem(tab.getPosition());
}
@Override
public void onTabUnselected(ActionBar.Tab tab, FragmentTransaction ft) {
}
@Override
public void onTabReselected(ActionBar.Tab tab, FragmentTransaction ft) {
}
};
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// add action menu here
MenuInflater inflater = getSupportMenuInflater();
inflater.inflate(R.menu.activity_itemlist, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle presses on the action bar items
switch (item.getItemId()) {
case R.id.add_item:
// openSearch();
Toast.makeText(context, " add_item ", Toast.LENGTH_SHORT).show();
return true;
case R.id.about:
// composeMessage();
Toast.makeText(context, " about", Toast.LENGTH_SHORT).show();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
class FragmentAdapter extends FragmentPagerAdapter implements
ViewPager.OnPageChangeListener {
private ViewPager mViewPager;
final int TOTAL_PAGES = 3;
private List<Fragment> fragments;
SparseArray<Fragment> registeredFragments = new SparseArray<Fragment>();
public FragmentAdapter(FragmentManager fm, ViewPager pager,
ActionBar actionBar, List<Fragment> fragmentsList) {
super(fm);
this.mViewPager = pager;
this.mViewPager.setOnPageChangeListener(this);
this.fragments = fragmentsList;
}
@Override
public Fragment getItem(int position) {
// switch (position) {
// case 0:
// return FragmentTab1.newInstance();
// case 1:
// return FragmentTab2.newInstance();
// case 2:
// return FragmentTab3.newInstance();
// default:
// throw new IllegalArgumentException(
// "The item position should be less or equal to:"
// + TOTAL_PAGES);
// }
return this.fragments.get(position);
}
@Override
public int getCount() {
// return TOTAL_PAGES;
return this.fragments.size();
}
public ViewPager getViewPager() {
return mViewPager;
}
// added newly
@Override
public Object instantiateItem(ViewGroup container, int position) {
Fragment fragment = (Fragment) super.instantiateItem(container,
position);
registeredFragments.put(position, fragment);
return fragment;
}
@Override
public void destroyItem(ViewGroup container, int position, Object object) {
registeredFragments.remove(position);
super.destroyItem(container, position, object);
}
public Fragment getRegisteredFragment(int position) {
return registeredFragments.get(position);
}
@Override
public void onPageScrollStateChanged(int arg0) {
}
@Override
public void onPageScrolled(int arg0, float arg1, int arg2) {
}
@Override
public void onPageSelected(int position) {
actionBar.setSelectedNavigationItem(position);
}
}
@Override
public void onBackPressed() {
Log.e(TAG_FRAGMENT, "onBackPressed");
FragmentManager fm = getSupportFragmentManager();
if (fm.getBackStackEntryCount() > 0) {
Log.i("MainActivity", "popping backstack");
fm.popBackStack();
} else {
Log.i("MainActivity", "nothing on backstack, calling super");
super.onBackPressed();
}
}
@Override
public void onContactSelected(ArrayList<Person> contactNumberlist) {
// data comes here, no problem.
this.blackListPersonList = contactNumberlist;
Log.d("onContactSelected", "onContactSelected");
// get error here
FragmentTab1 aFragmentTab1 = (FragmentTab1) mAdapter.getItem(0);
if (aFragmentTab1 != null) {
aFragmentTab1.updateFragment1(blackListPersonList);
}
FragmentTransaction transaction = getSupportFragmentManager()
.beginTransaction();
transaction.add(R.id.fragment_all_contacts_layout, aFragmentTab1);
transaction.commit();
}
public ArrayList<Person> getBlackListContacts() {
return blackListPersonList;
}
// public Fragment getFragment(ViewPager pager){
// Fragment theFragment = fragments.get(pager.getCurrentItem());
// return theFragment;
// }
}
FrgmentTab1看起来 。
public class FragmentTab1 extends SherlockFragment implements OnClickListener {
Button btnTest;
ViewPager pager;
LinearLayout layoutBlockNumbers;
LinearLayout layoutContact, layoutCallLog, layoutSMSLog, layoutManually;
public Context mContext;
CustomizedDialog dialog;
private static final int CONTACT_PICKER_RESULT = 1001;
private static final String DEBUG_TAG = "Contact List";
private static final double RESULT_OK = -1;
ListView listViewOnlyBlackListNumber;
ArrayList<Person> personList;
BlackListAdapter aBlackListAdapter;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragmenttab1, container,
false);
layoutBlockNumbers = (LinearLayout) rootView
.findViewById(R.id.layoutAddBlockNumbers);
layoutBlockNumbers.setOnClickListener(this);
listViewOnlyBlackListNumber = (ListView) rootView
.findViewById(R.id.listViewOnlyBlackListNumber);
personList = ((MainActivity) getActivity()).getBlackListContacts();
if (personList != null) {
aBlackListAdapter = new BlackListAdapter(getActivity(), personList,
m_onSelectedEventCalender);
listViewOnlyBlackListNumber.setAdapter(aBlackListAdapter);
} else {
listViewOnlyBlackListNumber.setEmptyView(container);
}
return rootView;
}
public void updateFragment1(ArrayList<Person> personList) {
// trying to update when came back here
aBlackListAdapter = new BlackListAdapter(getActivity(), personList,
m_onSelectedEventCalender);
listViewOnlyBlackListNumber.setAdapter(aBlackListAdapter);
aBlackListAdapter.notifyDataSetChanged();
}
}
在MainActivity里面的onContactSelected中获取错误。
10-30 00:22:29.674: E/AndroidRuntime(26834): FATAL EXCEPTION: main
java.lang.IllegalStateException: Can't change container ID of fragment FragmentTab1{42d27380 #0 id=0x7f040032 android:switcher:2130968626:0}: was 2130968626 now 2130968638
E/AndroidRuntime(26834): at android.support.v4.app.BackStackRecord.doAddOp(BackStackRecord.java:407)
E/AndroidRuntime(26834): at android.support.v4.app.BackStackRecord.add(BackStackRecord.java:384)
E/AndroidRuntime(26834): at com.mobigic.callblocker.MainActivity.onContactSelected(MainActivity.java:240)
希望,有人能帮帮我。
你的问题不是很清楚,尤其是关于你如何处理这些碎片的部分。比如你在显示 ShowAllContactFragment
片段放在哪个布局中?从你发的代码来看,你似乎是盲目地将 ShowAllContactFragment
的布局中,直接在包含 ViewPager
这是不对的。
与该错误相关的是,你得到了一个已经由 FragmentManager
通过适配器的 ViewPager
然后你再尝试在事务中添加它,动作会失败。如果你想显示之前显示的 FragmentTab1
片段,经过展示和工作。ShowAllContactFragment
片段,您应该尝试简单地删除最后记录的 FragmentManager
通过其 popBackStack...()
方法。
编辑。 我看了你的代码,但你做的事情还是很模糊。我看了一下主活动的布局,但是你没有一个id为 R.id.fragment_all_contacts_layout
所以我假设你是想插入新的 FragmentTab1
在旧有的布局中 FragmentTab1
这真的没有任何意义(更何况你还加上了 ShowAllContactFragment
容器的id为 R.id.fragmentTabLayout1
我也看不到)。) 总之,我假设你想要的是这个 ShowAllContactFragment
到 替换 的 FragmentTab1
来自 ViewPager
. 为此,你需要一个包装器片段来容纳两个嵌套的片段,并实现它们之间的通信。例如包装器片段。
public static class WrapperFragment extends Fragment implements
OnContactSelectedListener {
private static final String TAG_FIRST = "tag_first";
private static final String TAG_SECOND = "tag_second";
private static final int CONTENT_ID = 1000;
private FragmentTab1 mFrag1;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
FrameLayout content = new FrameLayout(getActivity());
content.setId(CONTENT_ID);
if (getChildFragmentManager().findFragmentByTag(TAG_SECOND) == null) {
mFrag1 = (FragmentTab1) getChildFragmentManager()
.findFragmentByTag(TAG_FIRST);
if (mFrag1 == null) {
mFrag1 = new FragmentTab1();
getChildFragmentManager().beginTransaction()
.add(CONTENT_ID, mFrag1, TAG_FIRST).commit();
}
}
return content;
}
@Override
public void onContactSelected(List<Person> contactNumberlist) {
getChildFragmentManager().popBackStackImmediate();
mFrag1.updateFragment1(contactNumberlist);
}
public void showPickerfragment() {
getChildFragmentManager().beginTransaction()
.replace(CONTENT_ID, new ShowAllContactFragment())
.addToBackStack(null).commit();
}
}
这将是你将会使用的片段 ViewPager
的适配器,而不是 FragmentTab1
片段。请注意,它实现了 OnContactSelectedListener
接口。你还需要对代码的其他部分进行一些修改。
@Override
public void onClick(View v) {
if (v == layoutCallLog) {
dialog.dismiss();
// make the wrapper fragment to open the ShowAllContactFragment fragment
((WrapperFragment) getParentFragment()).showPickerfragment();
// rest of the code
这个 ShowAllContactFragment
将需要修改,以便将选择事件发送到实现其接口的包装器片段。
@Override
public void onClick(View v) {
if (v == btnAdd) {
Toast.makeText(getActivity(), "" + blockListedPersonList.size(),
Toast.LENGTH_SHORT).show();
((OnContactSelectedListener) getParentFragment())
.onContactSelected(blockListedPersonList);
}
}
并在主活动中处理BACK按钮,当... ShowAllContactFragment
正在显示在 ViewPager
:
@Override
public void onBackPressed() {
if (mViewPager.getCurrentItem() == 0) { // I assumed 0 is the position in the adapter where the WrapperFragment will be used
Fragment targetPage = getSupportFragmentManager()
.findFragmentByTag("android:switcher:" + PAGER_ID + ":" + 0); // PAGER_ID is the id of the ViewPager
if (targetPage.getChildFragmentManager().getBackStackEntryCount() > 0) {
targetPage.getChildFragmentManager().popBackStack();
}
return;
}
super.onBackPressed();
}
请记住,你需要保存嵌套片段的数据。
我使用了 FragmentActivity
和 ViewPager
在不同的项目中,有两种解决方案。
1: 你可以使用 onHiddenChanged(boolean hidden)
在你 FragmentTab1
.
override fun onHiddenChanged(hidden: Boolean) {
// TODO Auto-generated method stub
if (!hidden) {
// check if personList size is changed
// and then call updateFragment1() methode
}
super.onHiddenChanged(hidden)
}
2:使用静态方法:你可以用 updateFragment1()
办法 static
所以当用户按 "ADD "时,调用 updateFragment1()
.
希望能帮到你