如何每隔一段时间刷新android选项卡片段?

如何每隔一段时间刷新android选项卡片段?,android,android-fragments,refresh,Android,Android Fragments,Refresh,我想刷新选项卡片段,但我该怎么做 我尝试刷新、重新创建,但不起作用。在此期间,它不会刷新,只会崩溃。如何在间隔时间刷新 选项卡活动 public class TabActivity extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener{ private SectionsPagerAdapter mSectionsPagerAdapter; /** * The {@

我想刷新选项卡
片段
,但我该怎么做

我尝试刷新、重新创建,但不起作用。在此期间,它不会刷新,只会崩溃。如何在间隔时间刷新

选项卡活动

 public class TabActivity extends AppCompatActivity implements     NavigationView.OnNavigationItemSelectedListener{


private SectionsPagerAdapter mSectionsPagerAdapter;

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

RecyclerView recyclerView;

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

    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);
    // Create the adapter that will return a fragment for each of the three
    // primary sections of the activity.
    mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());

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

    TabLayout tabLayout = (TabLayout) findViewById(R.id.tabs);

    mViewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout));
    tabLayout.addOnTabSelectedListener(new TabLayout.ViewPagerOnTabSelectedListener(mViewPager));


    DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
    ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
            this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
    drawer.addDrawerListener(toggle);
    toggle.syncState();

    NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
    navigationView.setNavigationItemSelectedListener(this);
    getSupportActionBar().setTitle("Trolley Count");




}




@Override
public void onBackPressed() {
    DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
    if (drawer.isDrawerOpen(GravityCompat.START)) {
        drawer.closeDrawer(GravityCompat.START);
    } else {
        super.onBackPressed();
    }
}
@SuppressWarnings("StatementWithEmptyBody")
@Override
public boolean onNavigationItemSelected(MenuItem item) {
    // Handle navigation view item clicks here.
    int id = item.getItemId();

    if (id == R.id.trolleycount) {
        startActivity(new Intent(getApplicationContext(),TabActivity.class));
    }  else if (id == R.id.alerts) {
        startActivity(new Intent(getApplicationContext(),alert.class));

    } else if (id == R.id.logout) {
        startActivity(new Intent(getApplicationContext(),MainActivity.class));

    }

    DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
    drawer.closeDrawer(GravityCompat.START);
    return true;
}
/**
 * A placeholder fragment containing a simple view.
 */
public static class PlaceholderFragment extends Fragment {
    /**
     * The fragment argument representing the section number for this
     * fragment.
     */
    private static final String ARG_SECTION_NUMBER = "section_number";

    public PlaceholderFragment() {
    }

    /**
     * Returns a new instance of this fragment for the given section
     * number.
     */
    public static PlaceholderFragment newInstance(int sectionNumber) {
        PlaceholderFragment fragment = new PlaceholderFragment();
        Bundle args = new Bundle();
        args.putInt(ARG_SECTION_NUMBER, sectionNumber);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View rootView = inflater.inflate(R.layout.fragment_tab, container, false);



        return rootView;
    }
}

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

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

    @Override
    public Fragment getItem(int position) {
        // getItem is called to instantiate the fragment for the given page.
        // Return a PlaceholderFragment (defined as a static inner class below).
        switch (position) {
            case 0:
                mSectionsPagerAdapter.notifyDataSetChanged();
                return new tab1allterminal();
            case 1:
                return new tab2t1();


            case 2:
                return new tab3t2();

            case 3:
                return new tab4t3();


            default:
                return null;
        }
    }

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

    @Override
    public int getItemPosition(Object object) {
        return POSITION_NONE;
    }
}

}
选项卡片段1

public class tab1allterminal extends Fragment implements Paginate.Callbacks {

public AdapterAdapter adapter;
public List<ListDataProvider> list;
public ListDataProvider listDataProvider;

RecyclerView recyclerView;

View rootView;


private boolean loading = false;
private int page = -1;
private Handler handler;
private Paginate paginate;
public  int total_page=1;




@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    // Inflate the layout for this fragment
    rootView = inflater.inflate(R.layout.fragment_tab1allterminal,container,false);

    recyclerView=rootView.findViewById(R.id.recycler_view);
    //Date currentTime = Calendar.getInstance().getTime();

    handler = new Handler();

    list = new ArrayList<>();
    adapter = new AdapterAdapter(getActivity(), list);

    recyclerView.setLayoutManager(new LinearLayoutManager(getActivity(), LinearLayoutManager.VERTICAL, false));
    recyclerView.addItemDecoration(new GridSpacingItemDecoration(1, dpToPx(10), true));
    recyclerView.setItemAnimator(new DefaultItemAnimator());
    recyclerView.setAdapter(adapter);






    page = -1;
    total_page=1;
    setupPagination();




    return rootView;
}



@Override
public void onLoadMore() {
    Log.d("Paginate", "onLoadMore");
    loading = true;
    // Fake asynchronous loading that will generate page of random data after some delay


    handler.postDelayed(fakeCallback, 1000);
}

@Override
public boolean isLoading() {
    return loading;
}
@Override
public boolean hasLoadedAllItems() {
    return page == total_page; // If all pages are loaded return true
}




private Runnable fakeCallback = new Runnable() {
    @Override
    public void run() {
        page++;

        getHostelsHttp();
        loading = false;

    }

};




protected void setupPagination() {
    // If RecyclerView was recently bound, unbind
    if (paginate != null) {
        paginate.unbind();
    }
    loading = false;



    paginate = Paginate.with(recyclerView, this)
            .setLoadingTriggerThreshold(2)
            .addLoadingListItem(true)
            .setLoadingListItemCreator(new CustomLoadingListItemCreator())

            .build();


}



private class CustomLoadingListItemCreator implements LoadingListItemCreator {
    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        LayoutInflater inflater = LayoutInflater.from(parent.getContext());
        View view = inflater.inflate(R.layout.cusom_loading, parent, false);
        return new VH(view);
    }

    @Override
    public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
        VH vh = (VH) holder;
        vh.tvLoading.setText(String.format("Total items loaded: %d.\nLoading more...", adapter.getItemCount()));

        // This is how you can make full span if you are using StaggeredGridLayoutManager
        if (recyclerView.getLayoutManager() instanceof StaggeredGridLayoutManager) {
            StaggeredGridLayoutManager.LayoutParams params = (StaggeredGridLayoutManager.LayoutParams) vh.itemView.getLayoutParams();
            params.setFullSpan(true);
        }
    }
}

static class VH extends RecyclerView.ViewHolder {
    TextView tvLoading;

    public VH(View itemView) {
        super(itemView);
        tvLoading = (TextView) itemView.findViewById(R.id.tv_loading_text);
    }
}

/**
 * RecyclerView item decoration - give equal margin around grid item
 */
public class GridSpacingItemDecoration extends RecyclerView.ItemDecoration {

    private int spanCount;
    private int spacing;
    private boolean includeEdge;

    public GridSpacingItemDecoration(int spanCount, int spacing, boolean includeEdge) {
        this.spanCount = spanCount;
        this.spacing = spacing;
        this.includeEdge = includeEdge;
    }

    @Override
    public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) {
        int position = parent.getChildAdapterPosition(view); // item position
        int column = position % spanCount; // item column

        if (includeEdge) {
            outRect.left = spacing - column * spacing / spanCount; // spacing - column * ((1f / spanCount) * spacing)
            outRect.right = (column + 1) * spacing / spanCount; // (column + 1) * ((1f / spanCount) * spacing)

            if (position < spanCount) { // top edge
                outRect.top = spacing;
            }
            outRect.bottom = spacing; // item bottom
        } else {
            outRect.left = column * spacing / spanCount; // column * ((1f / spanCount) * spacing)
            outRect.right = spacing - (column + 1) * spacing / spanCount; // spacing - (column + 1) * ((1f /    spanCount) * spacing)
            if (position >= spanCount) {
                outRect.top = spacing; // item top
            }
        }
    }
}

/**
 * Converting dp to pixel
 */
private int dpToPx(int dp) {
    Resources r = getResources();
    return Math.round(TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dp, r.getDisplayMetrics()));
}


private void getHostelsHttp() {
    RequestQueue queue = Volley.newRequestQueue(getActivity());
    Log.i("mytag", "start time: .");

    StringRequest myReq = new StringRequest(Request.Method.POST,
            Constants.URL_GET_DATA, new Response.Listener<String>() {
        @Override
        public void onResponse(String response) {
            try {
                Log.e("tag", "response " + response);
                JSONObject obj = new JSONObject(response);

                JSONObject jsonObject = obj.getJSONObject("data");
                JSONArray reqArr1 = jsonObject.getJSONArray("results");



                Log.e("myTag","total_page: "+ jsonObject.getInt("total_page"));

                total_page=jsonObject.getInt("total_page");


                Log.e("myTag", "try block");
                JSONObject resultsObj = null;
                for (int i = 0; i < reqArr1.length() - 1; i++) {
                    Log.e("myTag", "for block");
                    resultsObj=reqArr1.getJSONObject(i);
                    Log.e("myTag", resultsObj.getString("dock_id"));

                    listDataProvider=new ListDataProvider(resultsObj.getString("dock_id"),
                            resultsObj.getString("dock_name"),resultsObj.getString("trolley_count"),
                            resultsObj.getString("flight_arrival"));


                    list.add(listDataProvider);

                    adapter.notifyDataSetChanged();




                }

            }



            catch (JSONException e) {

            }



        }

    },
            new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {
                    Log.i("myTag", error.toString());

                }
            }) {

        @Override
        protected Map<String, String> getParams() {
            // Posting params to register url
            Map<String, String> params = new HashMap<String, String>();
            params.put("type", "all");
            params.put("current_page", String.valueOf(page));
            Log.e("myTag","Current page: "+page);
            return params;
        }

    };


    myReq.setRetryPolicy(new DefaultRetryPolicy(
            20000, DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT
    ));
    myReq.setShouldCache(false);
    queue.add(myReq);





}

public void refresh(int milliseconds){
    final Handler handler = new Handler();
    final Runnable runnable = new Runnable() {
        @Override
        public void run() {
        }
    };
    handler.postDelayed(runnable,milliseconds);
}

@Override
public void setUserVisibleHint(boolean isVisibleToUser) {
    super.setUserVisibleHint(isVisibleToUser);
    if (isVisibleToUser) {
        // Refresh your fragment here
        getFragmentManager().beginTransaction().detach(this).attach(this).commit();
        Log.i("IsRefresh", "Yes");
    }
}

}
public类tab1allterminal扩展片段实现Paginate.Callbacks{
公共适配器适配器;
公开名单;
公共ListDataProvider ListDataProvider;
回收视图回收视图;
视图根视图;
私有布尔加载=false;
私有整数页=-1;
私人经办人;
私人分页分页;
公共int总页数=1;
@凌驾
创建视图上的公共视图(布局、充气机、视图组容器、,
Bundle savedInstanceState){
//为该碎片膨胀布局
rootView=充气机。充气(右布局。碎片选项卡1所有终端,容器,假);
recyclerView=rootView.findViewById(R.id.recycler\u视图);
//Date currentTime=Calendar.getInstance().getTime();
handler=新的handler();
列表=新的ArrayList();
适配器=新适配器适配器(getActivity(),list);
setLayoutManager(新的LinearLayoutManager(getActivity(),LinearLayoutManager.VERTICAL,false));
recyclerView.addItemDecoration(新的GridSpacingItemDecoration(1,dpToPx(10),真));
setItemAnimator(新的DefaultItemAnimator());
recyclerView.setAdapter(适配器);
page=-1;
总页数=1;
设置分页();
返回rootView;
}
@凌驾
public void onLoadMore(){
Log.d(“分页”、“加载更多”);
加载=真;
//假异步加载,延迟一段时间后会生成一页随机数据
handler.postDelayed(fakeCallback,1000);
}
@凌驾
公共布尔isLoading(){
回装;
}
@凌驾
公共布尔hasLoadedAllItems(){
return page==total_page;//如果加载了所有页面,则返回true
}
private Runnable fakeCallback=new Runnable(){
@凌驾
公开募捐{
page++;
getHostelsHttp();
加载=假;
}
};
受保护的无效设置分页(){
//如果RecyclerView最近已绑定,请取消绑定
如果(分页!=null){
paginate.unbind();
}
加载=假;
paginate=paginate.with(recyclerView,this)
.setLoadingTriggerThreshold(2)
.addLoadingListItem(真)
.setLoadingListItemCreator(新的CustomLoadingListItemCreator())
.build();
}
私有类CustomLoadingListItemCreator实现LoadingListItemCreator{
@凌驾
public RecyclerView.ViewHolder onCreateViewHolder(视图组父级,int-viewType){
LayoutInflater充气器=LayoutInflater.from(parent.getContext());
视图=充气机。充气(R.layout.cusom_加载,父级,错误);
返回新的VH(视图);
}
@凌驾
BindViewHolder上的公共无效(RecyclerView.ViewHolder,int位置){
VH=(VH)支架;
vh.tvLoading.setText(String.format(“加载的项目总数:%d.\n加载更多…”),adapter.getItemCount());
//如果您使用的是StaggedGridLayoutManager,这就是如何实现完整跨度的方法
if(recyclerView.getLayoutManager()实例Of StaggedGridLayoutManager){
StaggedGridLayoutManager.LayoutParams参数=(StaggedGridLayoutManager.LayoutParams)vh.itemView.getLayoutParams();
参数setFullSpan(真);
}
}
}
静态级VH扩展了RecyclerView.ViewHolder{
文本视图加载;
公共VH(查看项目视图){
超级(项目视图);
tvLoading=(TextView)itemView.findViewById(R.id.tv\u loading\u text);
}
}
/**
*RecyclerView项目装饰-在网格项目周围提供相等的裕度
*/
公共类GridSpacingItemDecoration扩展了RecyclerView.ItemDecoration{
私人帐户;
私有整数间隔;
私有布尔包含边;
公共网格间距gitemdecoration(整数跨距计数、整数间距、布尔includeEdge){
this.spanCount=spanCount;
这个。间距=间距;
this.includeEdge=includeEdge;
}
@凌驾
public void getItemOffsets(Rect outRect、View View、RecyclerView父级、RecyclerView.State){
int position=parent.getChildAdapterPosition(视图);//项目位置
int column=位置%spanCount;//项目列
如果(包括边缘){
outRect.left=间距-列*间距/spanCount;//间距-列*((1f/spanCount)*间距)
outRect.right=(列+1)*间距/spanCount;/(列+1)*((1f/spanCount)*间距)
如果(位置=spanCount){
outRect.top=间距;//项目顶部
}
}
}
}
/**
*将dp转换为像素
*/
专用int dpToPx(int dp){
Resources r=getResources();
返回Math.round(TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP,dp,r.getDisplayMetrics());
}
私有void getHostelsHttp(){
RequestQueue=Volley.newRequestQueue(getActivity());
Log.i(“mytag”,“开始时间:”);
StringRequest myReq=新的StringRequest(Request.Method.POST,
Constants.URL_获取_数据,新响应。侦听器(){
@凌驾
公共void onResponse(字符串响应){
试一试{
Log.e(“标签”、“响应”+响应);
JSONObject obj=新的JSONObject(响应);
JSONObject JSONObject=obj.getJSONObject(“数据”);
JSONArray reqArr1=jsonObject.getJS