设置viewPager选项卡文本

时间:2016-06-23 06:26:54

标签: android android-fragments android-viewpager android-tablayout

我想在viewpager Fragments中从后台任务获取数据后设置viewPager选项卡文本。

现在发生了什么:我在viewpager中有3个片段。每个片段都运行一个asynctask,其结果用于更新viewpager选项卡文本。但是在片段的asynctask完成之前,viewpager设置标签文本会发生什么。我无法处理viewpager和片段之间的通信。

代码:

SlidingTab.xml(Viewpager xml):

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:app="http://schemas.android.com/apk/res-auto"
        xmlns:tools="http://schemas.android.com/tools"
        android:id="@+id/frame_main"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:background="@android:color/white"
        android:orientation="vertical"
        >

        <include
            android:id="@+id/toolbar1"
            layout="@layout/toolbar_job" />

        <com.RareMediaCompany.BDTrial.Utils.CustomTabLayout
            android:id="@+id/sliding_tabs"
            style="@style/CustomTabLayout"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:background="#eeeeee"
            app:tabIndicatorColor="#f39220"
            app:tabIndicatorHeight="3dp"
            app:tabMaxWidth="0dp"
            app:tabMode="fixed"
            app:tabPaddingEnd="0dp"
            app:tabPaddingStart="0dp"
 app:tabTextAppearance="@android:style/TextAppearance.Widget.TabWidget"
            app:tabSelectedTextColor="#808080" />
    <android.support.v4.view.ViewPager
            android:id="@+id/view_pager"
            android:layout_width="match_parent"
            android:layout_height="0dp"
            android:layout_weight="1"
            android:background="@android:color/white" />

    </LinearLayout>

Slidingtab.class(Viewpager类)

public class SlidingTab extends Fragment {

 public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View v = inflater.inflate(R.layout.sliding_tab, container, false);

        ((MainActivity) getActivity()).setActionBar(Html.fromHtml("<font color='#ffffff'>Assignments " + "</font>"));
        setHasOptionsMenu(true);


        initialise(v);

  return v;
    }

 private void initialise(View v) {
        context = getActivity();
        myprefs = new PreferenceforApp(context);
        activity = (AppCompatActivity) getActivity();
        handler = new Handler();
        viewPager = (ViewPager) v.findViewById(R.id.view_pager);
        viewPager.setOffscreenPageLimit(2);
        adapter = new PageAdapter(getChildFragmentManager(), context);
        viewPager.setAdapter(adapter);
        viewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {
                final InputMethodManager imm = (InputMethodManager) getActivity().getSystemService(
                        Context.INPUT_METHOD_SERVICE);
                imm.hideSoftInputFromWindow(viewPager.getWindowToken(), 0);


                if (bundle != null && bundle.size() != 0) {
                    if ((!bundle.getString("viewpager").equalsIgnoreCase("submit")) &&
                            (!bundle.getString("viewpager").equalsIgnoreCase("inProgress"))) {
                        slidingTab.getTabAt(0).setText("New (" + SingleTon.getInstance().getNewjob() + ")");
                        slidingTab.getTabAt(1).setText("In Progress (" + SingleTon.getInstance().getInprogressjob() + ")");
                        slidingTab.getTabAt(2).setText("Completed (" + SingleTon.getInstance().getCompletedjob() + ")");
                    }
                    bundle.clear();
                    handler.postDelayed(new setupTabs(),3000);
                } else {
                    slidingTab.getTabAt(0).setText("New (" + SingleTon.getInstance().getNewjob() + ")");
                    slidingTab.getTabAt(1).setText("In Progress (" + SingleTon.getInstance().getInprogressjob() + ")");
                    slidingTab.getTabAt(2).setText("Completed (" + SingleTon.getInstance().getCompletedjob() + ")");

                }

            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });

  slidingTab = (TabLayout) v.findViewById(R.id.sliding_tabs);
        slidingTab.setupWithViewPager(viewPager);

        if(!SingleTon.getInstance().getBoolean()){
            handler.postDelayed(new setupTabsDealyed(),3000);
        }else{
            handler.post(new setupTabs());
        }


    @Override
    public void onResume() {
        super.onResume();
        LocationManager locationManager = (LocationManager) getActivity().getSystemService(Context.LOCATION_SERVICE);

        if (bundle != null) {
            if (bundle.containsKey("viewpager")) {
                if (bundle.getString("viewpager").equalsIgnoreCase("submit")) {
                    viewPager.setCurrentItem(2, false);
                    SingleTon.getInstance().setBoolean(true);
                } else if (bundle.getString("viewpager").equalsIgnoreCase("inProgress")) {
                    viewPager.setCurrentItem(1, false);
                }

            }
        }

  private class setupTabs implements Runnable{

        @Override
        public void run() {


            slidingTab.getTabAt(0).setText("New (" + SingleTon.getInstance().getNewjob() + ")");
            slidingTab.getTabAt(1).setText("In Progress (" + SingleTon.getInstance().getInprogressjob() + ")");
            slidingTab.getTabAt(2).setText("Completed (" + SingleTon.getInstance().getCompletedjob() + ")");

        }
    }

    private class setupTabsDealyed implements Runnable{

        @Override
        public void run() {

            slidingTab.getTabAt(0).setText("New (" + SingleTon.getInstance().getNewjob() + ")");
            slidingTab.getTabAt(1).setText("In Progress (" + SingleTon.getInstance().getInprogressjob() + ")");
            slidingTab.getTabAt(2).setText("Completed (" + SingleTon.getInstance().getCompletedjob() + ")");

        }
    }
}

在上面的代码中,您将看到正在运行的2个线程正在通过Singleton中的数据更新选项卡文本,这是在Fragments中设置的。但是使用线程并不能解决问题。我也发现这不是一个好方法。

CustomTabLayout

public class  CustomTabLayout extends TabLayout {
    private Typeface mTypeface;
    public CustomTabLayout(Context context) {
        super(context);
        init();
    }
    public CustomTabLayout(Context context, AttributeSet attrs) {
        super(context, attrs);
        init();
    }
    public CustomTabLayout(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init();
    }
    private void init() {
//        mTypeface = Typeface.createFromAsset(getContext().getAssets(), "AvantGarde.ttf");
    }
    @Override
    public void setupWithViewPager(ViewPager viewPager) {
        super.setupWithViewPager(viewPager);
        if (mTypeface != null) {
            this.removeAllTabs();
            ViewGroup slidingTabStrip = (ViewGroup) getChildAt(0);
            PagerAdapter adapter = viewPager.getAdapter();
            for (int i = 0, count = adapter.getCount(); i < count; i++) {
                Tab tab = this.newTab();
                this.addTab(tab.setText(adapter.getPageTitle(i)));
                AppCompatTextView view = (AppCompatTextView) ((ViewGroup) slidingTabStrip.getChildAt(i)).getChildAt(1);
                view.setTypeface(mTypeface, Typeface.NORMAL);
            }
        }
    }
}

ViewPager适配器代码

public class PageAdapter extends FragmentStatePagerAdapter {
    private static final String TAG = "PageAdapter";
    public int newjob, inprogressjob, completedjob;
    final int PAGE_COUNT = 3;
    Fragment fragment;
    private String tabTitles[] = new String[]{"New", "In Progress", "Completed"};
    private Context context;
    HashMap<Integer,Fragment> map = new HashMap<>();
    public PageAdapter(FragmentManager fm, Context context) {
        super(fm);
        this.context = context;
    }


    @Override
    public Fragment getItem(int position) {
        Log.d(TAG, "New Instance Created :" + position);
        switch (position) {
            case 0:
                fragment = new JobFragment();
                map.put(position,fragment);
                return fragment;

            case 1:
                fragment=new InProgressJobFragment();
                map.put(position,fragment);
                return fragment;
            case 2:
                fragment = new CompletedJobFragment();
                map.put(position,fragment);
                return fragment;
        }
        return null;
    }


    public Fragment getFragment(int key) {
        return map.get(key);
    }

    public void set_current_position(int newjob, int inprogress, int completedjob) {
       this.newjob = newjob;
        this.inprogressjob = inprogress;
        this.completedjob = completedjob;

        notifyDataSetChanged();
    }


    @Override
    public CharSequence getPageTitle(int position) {
        int text = SingleTon.getInstance().getInprogressjob();
        switch (position) {
            case 0: return "New" + " (" + SingleTon.getInstance().getNewjob() + ")";
            case 1: return "In Progress" + " (" + SingleTon.getInstance().getInprogressjob() + ")";
            case 2: return "Completed" + " (" + SingleTon.getInstance().getCompletedjob() + ")";
        }
        return "";
    }

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

    private String getFragmentTag(int viewPagerId, int fragmentPosition)
    {
        return "android:switcher:" + viewPagerId + ":" + fragmentPosition;
    }
}

Fragment1的代码(其他2个具有相同代码的片段):

public class JobFragment extends BaseRefreshFragment {
  @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        v = inflater.inflate(R.layout.job_recyclerview, container, false);

        initialise(v);

//Asynctask
        new loadListTask().executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
 return v;
    }
 private void initialise(View v) {
        typeface = Typeface.createFromAsset(getActivity().getAssets(), "AvantGarde.ttf");
        listSize = 0;
        hashMap = new HashMap<>();
        context = getActivity();
        progressBar = (ProgressBar) v.findViewById(R.id.progress_bar);
        activity = (AppCompatActivity) getActivity();
        noEmployee = (TextView) v.findViewById(R.id.no_employee);
        recyclerView = (RecyclerView) v.findViewById(R.id.recycler_employee);
        maplayout = (LinearLayout)v.findViewById(R.id.mapview);
        mLayoutManager = new LinearLayoutManager(context);
        recyclerView.setLayoutManager(mLayoutManager);
        recyclerView.setItemAnimator(new CustomItemAnimator());
        recycleAdapter =  new JobAdapter(new ArrayList<Info>(), getActivity());
        recyclerView.setAdapter(recycleAdapter);
    }

private void setRecyclerView() {

        result = new ArrayList<Info>();

        ArrayList<RareMediaCompanyPlace> rmcPlaces;

        /*Find places*/
        rmcPlaces = RareMediaCompanyPlace.find(databaseServiceAndroid, null, rmcOrg, null);
        latLngs = new ArrayList<>();
        markers = new ArrayList<>();
        dataMap = new HashMap<>();

        for (int i = 0; i < rmcPlaces.size(); i++) {
            ArrayList<RareMediaCompanyOSD> osdArray = rmcPlaces.get(i).getOSDArray();



            for (int j = 0; j < osdArray.size(); j++) {
                if (osdArray.get(j).getName().equalsIgnoreCase("Place Details")) {
                    String placeDetails = osdArray.get(j).getValue();
                    WorkDescHolder holders = new WorkDescHolder();
                    Info info = new Info();
                    Gson gson = new Gson();
                    holders = gson.fromJson(placeDetails, WorkDescHolder.class);
                    if(holders.jobStatus == null || holders.jobStatus.equalsIgnoreCase("Downloaded")){
                                    /*OSD Array*/
                        latitude = rmcPlaces.get(i).getLocation().getLatitude();
                        longitude = rmcPlaces.get(i).getLocation().getLongitude();

                        LatLng latLng = new LatLng(latitude,longitude);
                        latLngs.add(latLng);

                        holders.placeUUID = rmcPlaces.get(i).getId().toString();
                        info.name = holders.companyName;
                        info.address = holders.address;
                        info.mobileNo = holders.phone;
                        info.descHolder = holders;
                        info.appontmentTimeMs = holders.assignedOnMS;
                        info.placeUUID = rmcPlaces.get(i).getId().toString();
                        info.jobNumber = holders.jobNumber;
                        info.emailId = holders.emailId;
                        info.spclInstruction = holders.specialInstruction;

                        Time timeobject = new Time();
                        timeobject.setToNow();
                        long nowmillis = timeobject.toMillis(false);
                        long appointmentMillis = Long.parseLong(holders.appointmentTime);
                        Date date = new Date(appointmentMillis);
                        SimpleDateFormat dateformat = new SimpleDateFormat("dd/MM , kk:mm");
                        info.time= dateformat.format(date);
                        long differnceMillis;
                        if (nowmillis > appointmentMillis) {
                            differnceMillis = nowmillis - appointmentMillis;
                            info.status = "Expired";

                        } else {
                            differnceMillis = appointmentMillis - nowmillis;
                            info.status = "Active";
                        }

                        if (holders.jobStatus == null || holders.jobStatus.equalsIgnoreCase("")) {
                            info.jobStatus = "Assigned";
                        } else if(holders.jobStatus.equalsIgnoreCase("Downloaded")){
                            info.jobStatus = "Assigned";
                        }else{
                            info.jobStatus = holders.jobStatus;
                        }


                        /*Get Time*/
                        String time = Utils.getDate(differnceMillis, "hh:mm dd/mmm/yyyy");

                        long days = differnceMillis / (24 * 60 * 60 * 1000);
                        differnceMillis -= days * (24 * 60 * 60 * 1000);

                        long hours = differnceMillis / (60 * 60 * 1000);
                        differnceMillis -= hours * (60 * 60 * 1000);

                        long minutes = differnceMillis / (60 * 1000);
                        differnceMillis -= minutes * (60 * 1000);

                        long seconds = differnceMillis / 1000;
     long diffSeconds = differnceMillis / 1000 % 60;
                    long diffMinutes = differnceMillis / (60 * 1000) % 60;
                    long diffHours = differnceMillis / (60 * 60 * 1000);
                    int diffInDays = (int) (differnceMillis / (1000 * 60 * 60 * 24));
                    String delay = "";

                        if (days > 0) {
                            delay += days + " days ";
                        }

                        if (hours > 0) {
                            if(days <2) {
                                delay += hours + " hrs ";
                            }
                        }
                        if(days <2) {
                            if(hours<1){
                                delay += minutes + " mins";
                            }
                        }


                        info.appointmentTime = delay;
                        Log.i("appointment Time", info.appointmentTime);
                        result.add(info);
                        Collections.sort(result, new Comparator<Info>() {
                            int str =0;
                            @Override
                            public int compare(Info lhs, Info rhs) {
                                str=lhs.time.compareTo(rhs.time);

                                return str;
                            }
                        });

                        dataMap.put(latLng,info);
                    }
                }
            }


        }

//Data setting for tabtext in viewpager
        SingleTon.getInstance().setNewjob(result.size());
        SingleTon.getInstance().setInfoArrayList(result)

    }

 private class loadListTask extends AsyncTask {

        @Override
        protected Object doInBackground(Object[] params) {
            setRecyclerView();
            return null;
        }

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            recycleAdapter.clearApplications();
            noEmployee.setVisibility(View.INVISIBLE);

            progressBar.setVisibility(View.VISIBLE);
            progressBar.getIndeterminateDrawable().setColorFilter(Color.parseColor("#727272"), PorterDuff.Mode.MULTIPLY);
            recyclerView.setVisibility(View.INVISIBLE);

        }

        @Override
        protected void onPostExecute(Object o) {
            setUpMapIfNeeded();

            recycleAdapter.addApplications(result);

            progressBar.setVisibility(View.INVISIBLE);
            if(result.size()>0) {
                recyclerView.setVisibility(View.VISIBLE);
            }else{
                noEmployee.setVisibility(View.VISIBLE);
            }
            super.onPostExecute(o);
        }
    }

}
  

请从代码或其他方法中帮助我,从片段中获取数据后,我可以从中更新tablayout的标签文本。

1 个答案:

答案 0 :(得分:0)

在每个片段中的asynctask的onPostExecute中调用Callback到PagerActivity并在那里使用。观看

https://github.com/eurosecom/inveantory/blob/master/app/src/main/java/com/eusecom/saminveantory/TabFragments/TabOneFragment.java

OnHeadlineSelectedListener mCallback;

// Container Activity must implement this interface
public interface OnHeadlineSelectedListener {
    public void onArticleSelected(int position);
}

@Override
public void onAttach(Activity activity) {
    super.onAttach(activity);

    // This makes sure that the container activity has implemented
    // the callback interface. If not, it throws an exception
    try {
        mCallback = (OnHeadlineSelectedListener) activity;
    } catch (ClassCastException e) {
        throw new ClassCastException(activity.toString()
                + " must implement OnHeadlineSelectedListener");
    }
}

.....

        protected void onPostExecute(String file_url) {
        // dismiss the dialog after getting all products
        pDialog.dismiss();
        // updating UI from Background Thread
        getActivity().runOnUiThread(new Runnable() {
            public void run() {

                adapter = new RVAdapter(getActivity(), getActivity(), mCountryModel);
                recyclerview.setAdapter(adapter);
                int pocx = mCountryModel.size();
                mCallback.onArticleSelected(pocx);

            }
        });

    }

https://github.com/eurosecom/inveantory/blob/master/app/src/main/java/com/eusecom/saminveantory/SearchRvActivity.java

import com.eusecom.saminveantory.TabFragments.TabOneFragment;

public class SearchRvActivity extends AppCompatActivity implements TabOneFragment.OnHeadlineSelectedListener {

....

public void onArticleSelected(int position) {
    // The user selected the headline of an article from the HeadlinesFragment
    // Do something here to display that article
    Toast.LENGTH_SHORT).show();

    String poss = position + "";
    tabLayout.removeAllTabs();
            tabLayout.addTab(tabLayout.newTab().setTag(0).setText(getResources().getString(R.string.popiseditname) + " " + poss));
    tabLayout.addTab(tabLayout.newTab().setTag(1).setText(getResources().getString(R.string.popisean)));
    tabLayout.addTab(tabLayout.newTab().setTag(1).setText(getResources().getString(R.string.popiscis)));

}