我希望在viewpager的fragments中从后台任务获取数据之后设置viewPager选项卡文本。
目前的情况是:我有三个在viewpager中运行的fragments。每个fragment都在运行一个异步任务,并且我使用这些任务的结果来更新viewpager选项卡文本。但是出现的问题是在fragment的异步任务完成之前,viewpager就已经设置了选项卡文本。我无法处理viewpager和fragments之间的通讯。
代码如下:
SlidingTab.xml(Viewpager xml):
在上述代码中,您将看到正在运行的2个线程,它们通过来自设置在片段中的Singleton的数据更新选项卡文本。但是即使使用线程也无法解决问题。我认为这不是一个好的方法。
CustomTabLayout:
请帮我提供一些代码或其他方法,使我能够在从片段获取数据后更新tablayout的选项卡文本。
目前的情况是:我有三个在viewpager中运行的fragments。每个fragment都在运行一个异步任务,并且我使用这些任务的结果来更新viewpager选项卡文本。但是出现的问题是在fragment的异步任务完成之前,viewpager就已经设置了选项卡文本。我无法处理viewpager和fragments之间的通讯。
代码如下:
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的数据更新选项卡文本。但是即使使用线程也无法解决问题。我认为这不是一个好的方法。
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的代码(其他两个片段具有相同的代码):
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的选项卡文本。