android - 如何从操作栏菜单刷新 fragment

标签 android android-fragments refresh

我有一个带有 fragment 的操作栏,如下所示。我想使用刷新按钮操作栏菜单刷新当前 fragment 。我看到很多使用 getFragmentByTag() 的示例,但我的 fragment 是动态创建的。请问如何获取当前 fragment 并刷新内容。

 
public class MainActivity extends FragmentActivity implements ActionBar.TabListener {<p></p>

RssFragmentPagerAdapter mRssFragmentPagerAdapter;

ViewPager mViewPager;

List<RssCategory> categoryList;
// Database Helper
private DatabaseHelper db;
private ActionBar actionBar;

public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    try{
        db = DatabaseHelper.getInstance(getApplicationContext());

        int categoryCount = db.getCategoriesCount();
        // Create the adapter that will return a fragment for each of the three primary sections
        // of the app.
        mRssFragmentPagerAdapter = new RssFragmentPagerAdapter(getSupportFragmentManager(), categoryCount);

        // Set up the action bar.
        actionBar = getActionBar();

        // Specify that the Home/Up button should not be enabled, since there is no hierarchical
        // parent.
        actionBar.setHomeButtonEnabled(false);

        // Specify that we will be displaying tabs in the action bar.
        actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
        //actionBar.setDisplayOptions(0, ActionBar.DISPLAY_SHOW_TITLE);
        // Set up the ViewPager, attaching the adapter and setting up a listener for when the
        // user swipes between sections.
        mViewPager = (ViewPager) findViewById(R.id.pager);
        mViewPager.setAdapter(mRssFragmentPagerAdapter);
        mViewPager.setOffscreenPageLimit(categoryCount - 1);
        mViewPager.setOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
            @Override
            public void onPageSelected(int position) {
                // When swiping between different app sections, select the corresponding tab.
                // We can also use ActionBar.Tab#select() to do this if we have a reference to the
                // Tab.
                actionBar.setSelectedNavigationItem(position);
            }
        });

        initialiseActionBar();
    }catch(Exception e){
        Log.e(getClass().getName(), e.getMessage());
    }
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    super.onCreateOptionsMenu(menu);

    MenuInflater inflater = getMenuInflater();
    inflater.inflate(R.menu.main, menu);
    return super.onCreateOptionsMenu(menu);        
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {

    switch (item.getItemId()) {

        case  android.R.id.home:
            this.finish();
            return true;

        case R.id.action_refresh:
            //TO REFRESH CURRENT Fragment
            return true;

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

private void initialiseActionBar() {

    if(categoryList == null)
        categoryList = db.getAllCategories();
    // For each of the sections in the app, add a tab to the action bar.
    for (RssCategory category : categoryList) {
        // 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
        // listener for when this tab is selected.
        actionBar.addTab(
                actionBar.newTab()
                        .setText(category.getName())
                        .setTabListener(this));
    }       
}

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

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

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

/**
 * A {@link FragmentPagerAdapter} that returns a fragment corresponding to one of the primary
 * sections of the app.
 */
public static class RssFragmentPagerAdapter extends FragmentPagerAdapter {
    private int pageCount;
    public RssFragmentPagerAdapter(FragmentManager fm, int pageCount) {
        super(fm);
        this.pageCount = pageCount;
    }

    @Override
    public Fragment getItem(int i) {
        switch (i) {

            default:
                // The other sections of the app are dummy placeholders.
                Fragment fragment = new RssFragment();
                Bundle args = new Bundle();
                args.putInt(RssFragment.ARG_CATEGORY_ID, i + 1);
                fragment.setArguments(args);
                return fragment;
        }
    }

    @Override
    public int getCount() {
        return pageCount;
    }

    /*@Override
    public CharSequence getPageTitle(int position) {
        return "Section " + (position + 1);
    }*/
}    

/**
 * A dummy fragment representing a section of the app, but that simply displays dummy text.
 */
public static class RssFragment extends Fragment {

    public static final String ARG_CATEGORY_ID = "category_id";
    View rootView;
    private List<RssItem> resultList;
    List<RssWebSite> websiteList;
    ArrayList<String> urlList;
    ProgressBar progressBar;

    @SuppressWarnings("unchecked")
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
        try{
            rootView = inflater.inflate(R.layout.fragment_rss_items_list, container, false);
            resultList = new ArrayList<RssItem>();
            progressBar = (ProgressBar)rootView.findViewById(R.id.progressBar);
            Bundle args = getArguments();
            if(args != null){
                DatabaseHelper db = DatabaseHelper.getInstance(rootView.getContext());
                websiteList = db.getAllRssWebSiteByCategory(args.getInt(ARG_CATEGORY_ID));
                urlList = new ArrayList<String>();
                if(websiteList != null && websiteList.size() > 0){
                    for (RssWebSite website : websiteList) {
                        urlList.add(website.getRssUrl());               
                    }
                    if(urlList.size() > 0) {
                        GetRSSDataTask task = new GetRSSDataTask();
                        task.execute(urlList);
                    }                       
                }
            }  
        }catch(Exception e){
            Log.e(getClass().getName(), e.getMessage());
        }
        return rootView;
    }

    /**
     * This class downloads and parses RSS Channel feed.
     * 
     * @author clippertech
     *
     */
    private class GetRSSDataTask extends AsyncTask<ArrayList<String>, Void, List<RssItem> > {

        @Override
        protected List<RssItem> doInBackground(ArrayList<String>... urls) {
            try {
                for(String url : urls[0]) {
                    // Create RSS reader
                    RssReader rssReader = new RssReader(url);
                    Log.d(getClass().getName(), url);
                    // Parse RSS, get items
                    resultList.addAll(rssReader.getItems());

                } 
                return resultList;
            }catch (Exception e) {
                Log.e(getClass().getName(), e.getMessage());
            }
            return null;
        }

        @Override
        protected void onPostExecute(List<RssItem> result) {            
            try{    
                // Get a ListView from the RSS Channel view
                ListView itcItems = (ListView) rootView.findViewById(R.id.rssChannelListView);

                View emptyView = null;

                if(result == null){
                    itcItems.setEmptyView(emptyView);
                    Log.d(getClass().getName(), "Empty View");
                }
                else {
                    //resultList.addAll(result);
                    Collections.sort(result, new Comparator<RssItem>() {

                        @Override
                        public int compare(RssItem lhs, RssItem rhs) {
                            SimpleDateFormat formatter = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss zzz");
                            try {
                                Date date1 = formatter.parse(rhs.getPublishedDate());
                                Date date2 = formatter.parse(lhs.getPublishedDate());
                                return date1.compareTo(date2);

                            } catch (ParseException e) {
                                // TODO Auto-generated catch block
                                e.printStackTrace();
                            }
                            return 0;
                        }
                    }); 
                    // Create a list adapter
                    ListAdapter adapter = new ListAdapter(rootView.getContext(), resultList);
                    itcItems.setAdapter(adapter);
                    adapter.notifyDataSetChanged();           
                    // Set list view item click listener
                    itcItems.setOnItemClickListener(new ListListener(resultList, getActivity()));
                }

                //dialog.dismiss();
                progressBar.setVisibility(View.GONE);
            }catch(Exception e){
                Log.e(getClass().getName(), e.getMessage());
            }
        }        
    }
}

最佳答案

您需要在 viewpager 中使用 PageChangeListener 来跟踪当前 fragment 索引。

您可以使用 fragment 索引从您的适配器中检索 fragment 并在其上调用您需要的任何方法。

关于android - 如何从操作栏菜单刷新 fragment ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19338487/

相关文章:

angularjs - Angular 应用程序如何处理刷新页面以及我们可以在加载指令上使用 $history

java - 在按钮 onclick 监听器中访问类的 MapView

android - 在 Android 中打开 Activity 之前显示进度条?

javascript - 使用 AJAX 和 FORM 自动刷新 DIV,按下按钮后有间隔

php - 从一个按钮基于变量 "id"刷新多个 iframe

android - 在 Android Studio 中创建 Activity 时,会创建两个布局,Activity 和 Fragment。我应该忽略 Activity 布局吗?

java - 无法执行dex : Multiple dex files define Ljavax/ws/rs/core/MultivaluedMap exception

android - 如何发送音频文件以存储在服务器中

android - 适用于Android的最佳Twitter API

android - 通过 Intent 额外通过电子邮件发送图像时发生 transactiontoolargeException