如何使用Tags运行活动中的片段方法?

时间:2013-05-05 14:58:34

标签: android android-fragments android-activity android-listfragment onresume

我有一个小应用程序,其中我使用eclipse创建了三个可滑动的选项卡。其中一个是常见的片段,而第二个和第三个是ListFragments,每个ListFragments都从Cursor获取它的数据。

我试验了它并希望删除数据库的内容,该内容是在托管活动的onCreate中创建的。我的问题是,当我删除数据时,第二个选项卡(其中一个ListFragments)在第三个选项卡时不会更新。

当第二个更新时,当我将手机置于睡眠状态时重新唤醒它,我认为,第二个标签不会进入其生命周期,因此它不会调用onResume。

两个ListFragments都使用相同的代码进行更新:

@Override
    public void onResume(){
        super.onResume();
        updateList();
        Log.i(TAG, "onResume");
    }

public void updateList(){
        dbCursor.requery();
        dbAdapter.notifyDataSetChanged();
        Log.i(TAG, "updateList");
    }

所以我尝试使用onTabSelected方法,但我总是得到一个NullPointerException,我想通过使用标签来避免,但我不能让它工作。

@Override
    public void onTabSelected(ActionBar.Tab tab,
            FragmentTransaction fragmentTransaction) {
        // When the given tab is selected, switch to the corresponding page in
        // the ViewPager.
        mViewPager.setCurrentItem(tab.getPosition());
        Log.e(TAG, String.valueOf(tab.getPosition()));
        switch(tab.getPosition()) {
        case 0:
            MenueFragment menu = new MenueFragment();
//          fragmentTransaction.add(menu, "1");//Eclipse wants to change Type of menu from MenueFragment to Fragment
//          menu = (MenueFragment) getFragmentManager().findFragmentByTag("1"); //My latest, not working approach...
            menu.updateList(); //In this Fragment updateList only does an entry into LogCat for testing.
            break;
        case 1: //These two following cases show how I tried it before.
            GefilterteListe fragment = new GefilterteListe();
            fragment.updateList(); 
            break;
        case 2:
            GesamteListe fragment2 = new GesamteListe();
            fragment2.updateList();
            break;
        }
        Log.i(TAG, "onTabSelected");
    }

Eclipse总是希望将我的Fragments的类型更改为其他Fragment类,并且在我想使用support.v4时需要android.app.fragment ...

如何让它工作,以便刷新两个ListFragments?
我是Fragments的新手,我知道Cursor-class已被折旧但我还没有时间理解装载机......:/

编辑:这是我的不工作ListFragment:

import android.content.Context;
import android.database.Cursor;
import android.os.Bundle;
import android.support.v4.app.ListFragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

public class GefilterteListe extends ListFragment{

    public static final String TAG = GefilterteListe.class.getSimpleName(); 

    private DatenbankHandler dbHandler;
    private Cursor dbCursor;
    private LehrerDatenbankAdapter dbAdapter;
    private Context mContext;

    public View OnCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState){
        Log.i(TAG, "GefilterteListe onCreate");
        View returnView = inflater.inflate(R.layout.plan, container, false);
        return returnView;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        dbHandler = new DatenbankHandler(getActivity());
        dbCursor = dbHandler.queryFilter();
        dbAdapter = new LehrerDatenbankAdapter(getActivity(), dbCursor);
        setListAdapter(dbAdapter);
        Log.i(TAG, "onCreate");
    }

    @Override
    public void onResume(){
        super.onResume();
        updateList();
        Log.i(TAG, "onResume");
    }

    /*@Override
    public void onPause(){
        super.onPause();
        updateList();
        Log.i(TAG, "onPause");
    }*/

    public void updateList(){
        dbCursor.requery();
        dbAdapter.notifyDataSetChanged();
        Log.i(TAG, "updateList");
    }

}

除了名称之外,它几乎与工作版相同,而另一个使用queryAll()而不是queryFilter()。

我的其他片段:

import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TextView;

public class MenueFragment extends Fragment {


    public static final String TAG = MenueFragment.class.getSimpleName();
    TextView text;
    Button button;
    DatenbankHandler dbHandler;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        Log.i(TAG, "MenueFragment onCreate");
        View returnView = inflater.inflate(R.layout.fragment_main_dummy, container, false);
        text = (TextView) returnView.findViewById(R.id.section_label);
        button = (Button) returnView.findViewById(R.id.button1);

        button.setOnClickListener(new OnClickListener(){

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                text.setText("Datenbank gelöscht.");
                dbHandler = new DatenbankHandler(getActivity());
                dbHandler.redoTbl();
            }

        });

        return returnView;
    }

    public void updateList(){
        Log.i(TAG, "updateList nonsense");
    }
 }

活动大致相同,就像Eclipse创建它一样。我只添加了我的碎片。
Edit2:这是我的托管活动:

public class HostActivity extends FragmentActivity implements ActionBar.TabListener {

    /**
     * The {@link android.support.v4.view.PagerAdapter} that will provide
     * fragments for each of the sections. We use a
     * {@link android.support.v4.app.FragmentPagerAdapter} derivative, which
     * will keep every loaded fragment in memory. If this becomes too memory
     * intensive, it may be best to switch to a
     * {@link android.support.v4.app.FragmentStatePagerAdapter}.
     */
    SectionsPagerAdapter mSectionsPagerAdapter;

    /**
     * The {@link ViewPager} that will host the section contents.
     */
    ViewPager mViewPager;

    private static final String TAG = HostActivity.class.getSimpleName();
    private DatenbankHandler dbHandler;

    private MenueFragment menueFragment;
    private GefilterteListe gefilterteListe;
    private GesamteListe gesamteListe;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
//      passwort("okidoki"); //Passwort Dialog
        setContentView(R.layout.activity_main);

        menueFragment = new MenueFragment();
        gefilterteListe = new GefilterteListe();
        gesamteListe = new GesamteListe();

        dbHandler = new DatenbankHandler(this);
        dbHandler.redoTbl();
        dbHandler.insert("T", "E", "S", "T", "This is a ", "Test.");
        dbHandler.insert("E", "E", "S", "T", "This is a ", "Test.");
        dbHandler.insert("S", "E", "S", "T", "This is a ", "Test.");
        dbHandler.insert("T ", "E", "S", "T", "This is a", "Test.");

        // Set up the action bar.
        final ActionBar actionBar = getActionBar();
        actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);

        // Create the adapter that will return a fragment for each of the three
        // primary sections of the app.
        mSectionsPagerAdapter = new SectionsPagerAdapter(
                getSupportFragmentManager());

        // Set up the ViewPager with the sections adapter.
        mViewPager = (ViewPager) findViewById(R.id.pager);
        mViewPager.setAdapter(mSectionsPagerAdapter);

        // When swiping between different sections, select the corresponding
        // tab. We can also use ActionBar.Tab#select() to do this if we have
        // a reference to the Tab.
        mViewPager
                .setOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
                    @Override
                    public void onPageSelected(int position) {
                        actionBar.setSelectedNavigationItem(position);
                    }
                });

        // For each of the sections in the app, add a tab to the action bar.
        for (int i = 0; i < mSectionsPagerAdapter.getCount(); i++) {
            // Create a tab with text corresponding to the page title defined by
            // the adapter. Also specify this Activity object, which implements
            // the TabListener interface, as the callback (listener) for when
            // this tab is selected.
            actionBar.addTab(actionBar.newTab()
                    .setText(mSectionsPagerAdapter.getPageTitle(i))
                    .setTabListener(this));
        }

    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.host, menu);
        return true;
    }

    @Override
    public void onTabSelected(ActionBar.Tab tab,
            FragmentTransaction fragmentTransaction) {
        // When the given tab is selected, switch to the corresponding page in
        // the ViewPager.
        mViewPager.setCurrentItem(tab.getPosition());
        /*Log.e(TAG, String.valueOf(tab.getPosition()));
        switch(tab.getPosition()) {
        case 0:
            MenueFragment menu = new MenueFragment();
//          fragmentTransaction.add(menu, "1");//Eclipse wants to change Type of menu from MenueFragment to Fragment
//          menu = (MenueFragment) getFragmentManager().findFragmentByTag("1"); //My latest, not working approach...
            menu.updateList();
            break;
        case 1:
            GefilterteListe fragment = new GefilterteListe();
            fragment.updateList();
            break;
        case 2:
            GesamteListe fragment2 = new GesamteListe();
            fragment2.updateList();
            break;
        }*/
//      updateAll();
        Log.i(TAG, "onTabSelected");
    }

    @Override
    public void onTabUnselected(ActionBar.Tab tab,
            FragmentTransaction fragmentTransaction) {
    }

    @Override
    public void onTabReselected(ActionBar.Tab tab,
            FragmentTransaction fragmentTransaction) {
    }

    /**
     * A {@link FragmentPagerAdapter} that returns a fragment corresponding to
     * one of the sections/tabs/pages.
     */
    public class SectionsPagerAdapter extends FragmentStatePagerAdapter {

        public SectionsPagerAdapter(FragmentManager fm) {
            super(fm);
        }

        @Override
        public Fragment getItem(int position) {
            Fragment frag = new Fragment();
            // getItem is called to instantiate the fragment for the given page.
            // Return a DummySectionFragment (defined as a static inner class
            // below) with the page number as its lone argument.
            switch(position) {
            case 0:
                MenueFragment menu = new MenueFragment();
                frag = menu;
                break;
            case 1:
                Fragment fragment = new GefilterteListe();
                frag = fragment;
                break;
            case 2:
                Fragment fragment2 = new GesamteListe();
                frag = fragment2;
                break;
            }
            return frag;
        }

        @Override
        public int getCount() {
            // Show 3 total pages.
            return 3;
        }

        @Override
        public CharSequence getPageTitle(int position) {
            Locale l = Locale.getDefault();
            switch (position) {
            case 0:
                return getString(R.string.title_section1).toUpperCase(l);
            case 1:
                return getString(R.string.title_section2).toUpperCase(l);
            case 2:
                return getString(R.string.title_section3).toUpperCase(l);
            }
            return null;
        }
    }

    public void updateAll() {       
        menueFragment.updateList();
        gefilterteListe.updateList();
        gesamteListe.updateList();
    }
}

1 个答案:

答案 0 :(得分:0)

尝试类似的东西:

interface DBchangesListener {
    public void updateList();
}

然后你的片段:

public class MenueFragment extends Fragment implements DBchangesListener {...}
public class GefilterteListe extends Fragment implements DBchangesListener {...}
public class GesamteListe extends Fragment implements DBchangesListener {...}

在活动中:

private MenueFragment menueFragment;
private GefilterteListe gefilterteListe;
private DBchangesListener gesamteListe;

然后在onCreate()

menueFragment = new MenueFragment();
gefilterteListe = new GefilterteListe();
gesamteListe = new GesamteListe();

添加您现在正在添加的片段。
接下来在您的活动中创建简单的方法:

public void updateAll() {
    menueFragment.updateList();
    gefilterteListe.updateList();
    gesamteListe.updateList();
}

在数据库更改结束时,只需调用updateAll()即可更新所有片段。