4

好吧,考虑我有两个片段FragmentTab1ShowAllContactFragmentFragmentTab1包含一个列表视图& 和一个按钮。单击按钮时,我会在我的 viewpager 中替换 ShowAllContactFragment。当显示ShowAllContactFragment时,用户可以通过选择列表视图中的复选框来选择多个联系人,并且它还有一个添加联系人按钮。

我需要什么:我想更新 FragmentTab1 中的现有列表视图,当用户按下ShowAllContactFragment 中的ADD按钮时,在此列表视图中选择一些联系人后。我还删除了 ShowAllContactFragment,并在发生这种情况时显示 FragmentTab1。

我的解决状态:我关注android 开发者论坛,通过 Activity 在片段之间进行数据通信。我马上就好。我在 MainActivity 的 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();

我的 MainActivity 和 FragmentAdapter 看起来:

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;
    // }

}

FragmentTab1 看起来:

  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)

希望,有人帮助我。

4

2 回答 2

1

我在不同的项目中使用FragmentActivityViewPager,有两种解决方案:

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,因此当用户按下“添加”时,调用updateFragment1().

希望能帮助到你。

于 2013-11-11T19:34:03.357 回答
1

您的问题不是很清楚,尤其是关于如何处理这些片段的部分。就像当你展示ShowAllContactFragment你把它放在哪个布局中的片段时一样?从您发布的代码看来,您似乎是在盲目地将ShowAllContactFragment片段直接添加到包含ViewPager不正确的布局中。

FragmentManager与错误相关的是,您通过 的适配器获得对已经由 管理的片段之一的引用,ViewPager然后您重试将其添加到事务中,该操作将失败。如果您尝试显示之前显示的FragmentTab1片段,则在显示并使用该片段之后,您应该尝试通过其方法之一ShowAllContactFragment简单地删除最后记录的动作。FragmentManagerpopBackStack...()

编辑:我查看了您的代码,但您所做的仍然模棱两可。我已经查看了主要活动的布局,但是您没有带有 id 的容器,R.id.fragment_all_contacts_layout所以我假设您正试图以某种方式FragmentTab1在旧的布局中插入新的,FragmentTab1这真的没有任何意义(更不用说你将ShowAllContactFragmentid 添加到R.id.fragmentTabLayout1我也看不到的容器中)。无论如何,我假设您ShowAllContactFragment想要替换. 为此,您需要一个包装片段来保存两个嵌套片段并启用它们之间的通信。例如包装片段:FragmentTab1ViewPager

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();
}

请记住,您需要保存嵌套片段的数据。

于 2013-11-05T12:51:59.707 回答