在Fragment.OnCreateView()之外获取片段活动

时间:2015-04-10 19:19:31

标签: android android-fragments

我有Fragment TableLayout。表中的数据来自SQLite数据库。 SQLite数据库是从MainActivity中的AsyncTask中的RESTful Web服务填充的。在填充表之前,Fragment必须等待任务完成。 Fragment侦听要调用的任务onPostExecute()方法。如果是,则调用onLoadAndStoreComplete中的方法Fragment。这一切都有效。

什么行不通的是我需要片段活动才能在TableRows中创建新的TextViewsonLoadAndStoreComplete而我无法得到它。

我试过了:
- 创建一个班级成员fragmentActivity并在onCreateView()中进行分配,但到达onLoadAndStoreComplete()时,它为空。
- 在this.getActivity()中再次调用onLoadAndStoreComplete(),但它返回null。

如何获取片段活动?

MyFragment.java:

public View onCreateView(LayoutInflater inflater, ViewGroup container,  Bundle savedInstanceState) {
        fragmentActivity = this.getActivity(); // return value is valid
        ...
}

@Override                               
public void onLoadAndStoreComplete() {  

        fragmentActivity = this.getActivity(); // returns null
    ...
}
来自MainActivity.java的

(扩展ActionBarActivity)

@Override
protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mainActivity = this;
        setContentView(R.layout.activity_main);

        Resources resources = getResources();
        String[] tabTitleArray = { resources.getString(R.string.first_fragment),  
                                   resources.getString(R.string.second_fragment),  
                                   resources.getString(R.string.help_fragment) };

        viewPager = (ViewPager) findViewById(R.id.pager);
        actionBar = getSupportActionBar();
        mAdapter = new TabsPagerAdapter(this.getSupportFragmentManager());

        viewPager.setAdapter(mAdapter);
        actionBar.setHomeButtonEnabled(false);
        actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);        

        for (String tab_name : tabTitleArray) {
            actionBar.addTab(actionBar.newTab().setText(tab_name).setTabListener(this));
        }

        // On swiping the ViewPager, select the respective tab 
        viewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {

            @Override
            public void onPageSelected(int position) {
                actionBar.setSelectedNavigationItem(position) ;// on changing the page, make respected tab selected
            }
            @Override
            public void onPageScrolled(int arg0, float arg1, int arg2) {
            }
            @Override
            public void onPageScrollStateChanged(int arg0) {
            }
        });

        String url = "http://myrestfulwebservice";
        Fragment secondFragment = mAdapter.getItem(SECOND_TAB);
            new LoadAndStoreDataTask((OnLoadAndStoreCompleteListener)secondFragment).execute(url);    
    }

} // end OnCreate

TabsPagerAdapter.java

public class TabsPagerAdapter extends FragmentPagerAdapter {

    public TabsPagerAdapter(FragmentManager fragmentManager) {
        super(fragmentManager);
    }

    @Override
    public Fragment getItem(int index) {
        switch (index) {
        case 0:
            return new FirstFragment();
        case 1:
            return new SecondFragment();
        case 2:
            return new HelpFragment();
        }

        return null;
    }

    @Override
    public int getCount() {
        return 3; // get item count - equal to number of tabs
    }

    public static void setTabColor(TabHost tabhost) {
        for(int i=0;i<tabhost.getTabWidget().getChildCount();i++) {
            tabhost.getTabWidget().getChildAt(i).setBackgroundColor(Color.parseColor("#FF0000")); //unselected
        }
        tabhost.getTabWidget().getChildAt(tabhost.getCurrentTab()).setBackgroundColor(Color.parseColor("#0000FF")); // selected
    }

}

2 个答案:

答案 0 :(得分:2)

我没有测试过这个,但在我看来它会起作用。

ContextTabsPagerAdapter的构造函数添加MyFragment参数。

这样的事情:

TabsPagerAdapter.java:

public class TabsPagerAdapter extends FragmentPagerAdapter {

    private Context mCtx;

    public TabsPagerAdapter(FragmentManager fragmentManager, Context context) {
        super(fragmentManager);
        mCtx = context;
    }

    @Override
    public Fragment getItem(int index) {
        switch (index) {
        case 0:
            return new FirstFragment(mCtx);
        case 1:
            return new SecondFragment(mCtx);
        case 2:
            return new HelpFragment(mCtx);
        }

        return null;
    }

    @Override
    public int getCount() {
        return 3; // get item count - equal to number of tabs
    }

    public static void setTabColor(TabHost tabhost) {
        for(int i=0;i<tabhost.getTabWidget().getChildCount();i++) {
            tabhost.getTabWidget().getChildAt(i).setBackgroundColor(Color.parseColor("#FF0000")); //unselected
        }
        tabhost.getTabWidget().getChildAt(tabhost.getCurrentTab()).setBackgroundColor(Color.parseColor("#0000FF")); // selected
    }

}

MainActivity.java:

  mAdapter = new TabsPagerAdapter(this.getSupportFragmentManager(), this);

MyFragment.java(在FirstFragmentSecondFragmentHelpFragment中执行此操作):

public static class MyFragment extends Fragment {

    private Context fragmentActivity ;

    public MyFragment(Context context){
        fragmentActivity  = context;
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        //.........            
        return rootView;
    }

    @Override
    public void onLoadAndStoreComplete() {

        //do something with fragmentActivity

    }
}

答案 1 :(得分:1)

看起来AsyncTask太早开始了。建议在 onActivityCreated() 中加载数据库,在onCreateView之后调用

@Override
public void onActivityCreated (Bundle savedInstanceState) {
    //load your db here
}