每次单击android中的选项卡时,重新加载片段中的数据

时间:2014-02-03 17:59:17

标签: android android-fragments

我已经创建了一个应用程序布局在Android 2.3中有三个选项卡。每个选项卡都有一个片段,每个片段中都有一个列表视图。列表视图中显示的所有数据都来自互联网,数据总是在变化,因此每次观看该片段时我都想重新加载数据。例如,我现在正在观看“tab1”,当我点击“tab2”时,“tab2”中的数据将重新加载,当我点击“tab1”时,“tab1”中的数据也将重新加载。我试过了

ft.detach(frg); ft.attach(frg); ft.commit();

但总是有错误。

这是我的代码。

MainActivity

public class MainActivity extends ActionBarActivity {

    private ViewPager pager;
    private TabsAdapter mTabsAdapter;

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

        pager = new ViewPager(this);
        pager.setId(R.id.pager);
        setContentView(pager);

        final ActionBar bar = getSupportActionBar();  
        bar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);

        mTabsAdapter = new TabsAdapter(this, getSupportActionBar(), pager);
        mTabsAdapter.addTab(bar.newTab().setText("tab1"), Tab1.class, null);
        mTabsAdapter.addTab(bar.newTab().setText("tab2"), Tab2.class, null);
        mTabsAdapter.addTab(bar.newTab().setText("tab3"), Tab3.class, null);
    }
}

Tab1

public class Tab1 extends ListFragment{
    private String result;
    protected ArrayAdapter listAdapter;
    private ArrayList<String> items = new ArrayList<String>();
    final String uri = "http://localhost/sample.php";

    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState){
        View rootView = inflater.inflate(R.layout.list, container, false);
        items.clear();
        Thread t = new Thread(new sendPostRunnable());
        t.start();
        listAdapter = new ArrayAdapter<String>(getActivity(), android.R.layout.simple_list_item_1, items);
        setListAdapter(listAdapter);
        return rootView;
    }

    class sendPostRunnable implements Runnable{
        @Override
        public void run(){
            result = sendPostDataToInternet();
            String temp = "Not result.";
            try {
                JSONTokener jsonTokener = new JSONTokener(result); 
                JSONObject jsonObject = (JSONObject) jsonTokener.nextValue(); 
                JSONArray jarray = jsonObject.getJSONArray("response");
                for (int i = 0; i < jarray.length(); i++) { 
                    temp = "";
                    JSONObject jobject = jarray.getJSONObject(i); 
                    temp += "Name: "+jobject.getString("name")+"\n"; 
                    temp += "Email: "+jobject.getString("email"); 
                    items.add(temp);
                    temp = "";
                } 
                if(jarray.length() < 1){
                    items.add(temp);
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }

            getActivity().runOnUiThread(new Runnable() {
                public void run() {
                    listAdapter.notifyDataSetChanged();
                }
            });

        }
    }

    private String sendPostDataToInternet(){
        HttpPost httpRequest = new HttpPost(uri);
        List<NameValuePair> params = new ArrayList<NameValuePair>();
        try{
            httpRequest.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8));
            HttpResponse httpResponse = new DefaultHttpClient().execute(httpRequest);
            if (httpResponse.getStatusLine().getStatusCode() == 200){
                String strResult = EntityUtils.toString(httpResponse.getEntity());
                return strResult;
            }
        } catch (Exception e){
            e.printStackTrace();
        }
        return null;
    }
}

TabsAdapter

public class TabsAdapter extends FragmentPagerAdapter implements TabListener, OnPageChangeListener{
    private final Context mContext;
    private final ActionBar mActionBar;
    private final ViewPager mViewPager;
    private final ArrayList<TabInfo> mTabs = new ArrayList<TabInfo>();
    private final String TAG = "";

    static final class TabInfo{
        private final Class<?> clss;
        private final Bundle args;

        TabInfo(Class<?> _class, Bundle _args){
            clss = _class;
            args = _args;
        }
    }

    public TabsAdapter(FragmentActivity activity, ActionBar bar, ViewPager pager) {
        super(activity.getSupportFragmentManager());
        mContext = activity;
        mActionBar = bar;
        mViewPager = pager;
        mViewPager.setAdapter(this);
        mViewPager.setOnPageChangeListener(this);

    }

    public void addTab(Tab tab, Class<?> clss, Bundle args){
        TabInfo info = new TabInfo(clss, args);
        tab.setTag(info);
        tab.setTabListener(this);
        mTabs.add(info);
        mActionBar.addTab(tab);
        notifyDataSetChanged();
    }

    @Override
    public void onPageSelected(int position) {
        mActionBar.setSelectedNavigationItem(position); 
    }

    @Override
    public void onTabSelected(Tab tab, FragmentTransaction ft) {
        mViewPager.setCurrentItem(tab.getPosition());
        Log.v(TAG, "clicked");
        Object tag = tab.getTag();
        for (int i = 0; i<mTabs.size(); i++){
            if (mTabs.get(i) == tag){
                mViewPager.setCurrentItem(i);
            }
        }
    }

    @Override
    public Fragment getItem(int position) {
        TabInfo info = mTabs.get(position);
        return Fragment.instantiate(mContext, info.clss.getName(), info.args);
    }

    @Override
    public int getCount() {
        return mTabs.size();
    }
}

2 个答案:

答案 0 :(得分:0)

在片段中实现OnMyRefreshListener之类的界面,然后:

public void onPageSelected(int position) { 
    ((OnMyRefreshListener)pagerViewAdapter.getItem()).onMyRefresh();
}

答案 1 :(得分:0)

我在之前的应用中面临同样的问题。

只需在 MainActivity.java

中添加一行即可

<强> viewPager.setOffscreenPageLimit();

如果您有三个标签,则放入viewPager.setOffscreenPageLimit(3);.

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

        viewPager = (ViewPager) findViewById(R.id.viewpager);
        viewPager.setOffscreenPageLimit(4);
        setupViewPager(viewPager);

        tabLayout = (TabLayout) findViewById(R.id.tabs);
        tabLayout.setupWithViewPager(viewPager);
        setupTabIcons();
    }

Document