如何在来自父片段活动的viewpager中的两个listfragments之间进行通信

时间:2013-10-09 13:35:24

标签: java android android-fragments android-viewpager android-listfragment

基本上我有一个片段活动,它包含两个 ListFragments ,我使用 ViewPager 在它们之间滑动。我点击一个片段在listItem上选择Add Phrase,它会更新另一个listFragment的数据库,但在我关闭应用程序并重新打开之前不会立即刷新。我尝试使用官方的android方式在fragment之间进行通信,使用listFragment中的接口和回调方法http://developer.android.com/training/basics/fragments/communicating.html。这应该调用填充第二个ListFragment中的数据的方法,但我总是得到nullPionterException。请帮帮我

这是第一个ListFragment(BoardActivity.java,只是添加界面的部分)

//container activity must implement this interface
public interface OnAddPhraseListener {
    public void onAddPhrase(String text);
}

@Override
public void onAttach(Activity activity){
    super.onAttach(activity);

    //make sure that the container activity has implemented the callback interface
    try{
        mAddPhraseCallback = (OnAddPhraseListener) activity;
    }catch(ClassCastException e){

    }
}

这是第二个ListFragment(PhrasesActivity.java,用数据填充ListView的部分)

public void fillData(){
    try {
        mDbHelper = new PhrasesDbAdapter(this.getSherlockActivity()).open();
    } catch (SQLException e) {
        Log.e(tag, "Couldnt open mDbHelper to fill Data");
        e.printStackTrace();
    }
    Cursor phraseCursor = mDbHelper.fetchAllPhrases();
    String [] from = new String[]{PhrasesDbAdapter.KEY_PHRASE};
    int [] to = new int []{R.id.phraseText};
    SimpleCursorAdapter phrases = new SimpleCursorAdapter(getSherlockActivity(), R.layout.phrases_row, phraseCursor, from, to);
    setListAdapter(phrases);
}

这是 MainLayoutActivity ,其中包含 BoardActivity PhrasesActivity

的viewpager
public class MainLayoutActivity extends SherlockFragmentActivity implements OnAddPhraseListener {

    public ViewPager mViewPager;
    public ViewPagerAdapter mAdapter;
    public com.actionbarsherlock.app.ActionBar mActionBar;
    public Tab tab;
    ComponentName service;
    final String CLIP_CHANGED = "clipboard.clipchanged";
    final String tag = "Clipboard";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.layout_main);

        mActionBar = getSupportActionBar();
        mActionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);

        setUpView();
        setTab();

        service = startService(new Intent(this, ClipboardService.class));
    }
    @Override
    public boolean onCreateOptionsMenu(com.actionbarsherlock.view.Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getSupportMenuInflater().inflate(R.menu.menu_layout, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(com.actionbarsherlock.view.MenuItem item){

        switch (item.getItemId()) {
            case R.id.menu_settings:
                Intent intent = new Intent(this, ClipboardPrefereneActivity.class);
                startActivity(intent);
                return true;

            case R.id.menu_about:
                return true;

            default:
                return super.onOptionsItemSelected(item);
        }
    }

    private void setUpView(){
        mViewPager = (ViewPager) findViewById(R.id.pager);
        mAdapter = new ViewPagerAdapter(getApplicationContext(), getSupportFragmentManager());
        mViewPager.setAdapter(mAdapter);
        mViewPager.setCurrentItem(0);
    }

    private void setTab(){
        mViewPager.setOnPageChangeListener(new OnPageChangeListener(){

            @Override
            public void onPageScrollStateChanged(int arg0) {

            }
            @Override
            public void onPageScrolled(int arg0, float arg1, int arg2) {

            }
            @Override
            public void onPageSelected(int position) {

                mActionBar.setSelectedNavigationItem(position);
            }
        });

        ActionBar.TabListener tabListener = new ActionBar.TabListener() {

            @Override
            public void onTabUnselected(Tab tab, FragmentTransaction ft) {

            }

            @Override
            public void onTabSelected(Tab tab, FragmentTransaction ft) {
                mViewPager.setCurrentItem(tab.getPosition());
            }

            @Override
            public void onTabReselected(Tab tab, FragmentTransaction ft) {

            }
        };

        tab = mActionBar.newTab().setText("Board").setTabListener(tabListener);
        mActionBar.addTab(tab);

        tab = mActionBar.newTab().setText("Phrases").setTabListener(tabListener);
        mActionBar.addTab(tab);
    }
    @Override
    public void onAddPhrase(String text) {
        Log.d(tag, "On Add Phrase callback >>>>>>>>>>>>");
        PhrasesActivity phrasesActivity = (PhrasesActivity) getSupportFragmentManager().findFragmentById(R.id.tab_phrases);

        if(phrasesActivity != null){
            Log.e(tag, "Got Phrases Activity to fill Data");
            phrasesActivity.fillData();
        }
        else{
            Log.e(tag, "Couldnt get Phrases Activity to fill Data");

        }
    }
}

应用程序始终会显示日志消息 Log.e(tag, "Couldnt get Phrases Activity to fill Data");

我再次阅读有关LocalBraodcastManager的信息,我可以用这个来刷新吗?这是一种更好的方式吗? http://getpocket.com/a/read/156004495

1 个答案:

答案 0 :(得分:0)

请勿在ViewPager场景中找到FragmentByTag,因为无法通过自己的原因获取标记。使用LocalBroadcastManager代替片段之间的通信。