【问题标题】:Android :Unable to reload the fragments with the updated content from the serverAndroid:无法使用来自服务器的更新内容重新加载片段
【发布时间】:2016-09-21 15:47:09
【问题描述】:

我有一个 Fragment 作为容器,它有一个 tablayout 和一个 viewpager,它有 2 个 tab 片段。在主容器片段中,我有一个带有自定义按钮的工具栏,该按钮通过点击 web 服务来更新选项卡片段中的内容。

这是容器片段的代码。

public class NotificationsFragment extends Fragment {

TabLayout tabLayout = null;
ViewPager viewPagerNotifications = null;

public NotificationsFragment()
 {
     // Required empty public constructor
}

public static NotificationsFragment newInstance() {

    Bundle args = new Bundle();

    NotificationsFragment fragment = new NotificationsFragment();
    fragment.setArguments(args);
    return fragment;
}

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

    ViewGroup rootView = (ViewGroup) inflater.inflate(R.layout.fragment_notifications, null);

    final Button mButton_right = (Button) getActivity().findViewById(R.id.Button_right);
    mButton_right.setVisibility(View.VISIBLE);

    final Button mButton_alerts = (Button) getActivity().findViewById(R.id.Button_alerts);
    mButton_alerts.setVisibility(View.GONE);

    tabLayout = (TabLayout) rootView.findViewById(R.id.TabLayout_notifications);
    tabLayout.addTab(tabLayout.newTab().setText("Symptoms"));
    tabLayout.addTab(tabLayout.newTab().setText("Diagnosis"));

    tabLayout.setTabGravity(TabLayout.GRAVITY_FILL);
    tabLayout.setSelectedTabIndicatorColor(getResources().getColor(R.color.textColorPrimary));
    tabLayout.setSelectedTabIndicatorHeight(8);
    tabLayout.setTabTextColors(ContextCompat.getColor(getActivity(),R.color.textColorPrimary),
            getResources().getColor(R.color.textColorPrimary));

    ViewCompat.setElevation(tabLayout, 5f);

    viewPagerNotifications = (ViewPager) rootView.findViewById(R.id.viewPagernotifications);


    final NotificationPagerAdapter pagerAdapter = new NotificationPagerAdapter(getFragmentManager(),tabLayout.getTabCount());
    viewPagerNotifications.setAdapter(pagerAdapter);

    viewPagerNotifications.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout));

    viewPagerNotifications.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
        @Override
        public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

        }

        @Override
        public void onPageSelected(int position) {

            Log.e("notif","onpageselected"+position);


        }

        @Override
        public void onPageScrollStateChanged(int state) {

        }
    });

    tabLayout.setOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
        @Override
        public void onTabSelected(TabLayout.Tab tab) {
            viewPagerNotifications.setCurrentItem(tab.getPosition());

            switch (tab.getPosition())
            {
                case 0:
                    mButton_right.setVisibility(View.VISIBLE);
                    mButton_alerts.setVisibility(View.GONE);

                   /* LocalBroadcastManager lbm = LocalBroadcastManager.getInstance(getActivity());
                    Intent i = new Intent("TAG_REFRESH");
                    lbm.sendBroadcast(i);*/

                    break;

                case 1:
                    mButton_right.setVisibility(View.GONE);
                    mButton_alerts.setVisibility(View.VISIBLE);

                    break;

                default:
                    break;
            }



        }

        @Override
        public void onTabUnselected(TabLayout.Tab tab) {

        }

        @Override
        public void onTabReselected(TabLayout.Tab tab) {

        }
    });




    // Inflate the layout for this fragment
    return rootView;
}


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


@Override
public void onDetach() {
    super.onDetach();
}

}

这是 Pager Adapter 类的代码

public class NotificationPagerAdapter extends FragmentStatePagerAdapter {

final int Illness = 1;
final int Symptoms = 0;

int numOfTabs;

SymptomsTabFragment symptomsTabFragment;
IllnessTabFragment illnessTabFragment;


public NotificationPagerAdapter(FragmentManager fm,int numOfTabs) {
    super(fm);
    this.numOfTabs=numOfTabs;
}

@Override
public Fragment getItem(int position) {
    switch (position)
    {
        case Symptoms:
           symptomsTabFragment = new SymptomsTabFragment();
            return symptomsTabFragment;

        case Illness:
             illnessTabFragment= new IllnessTabFragment();
            return illnessTabFragment;


    }
    return null;
}


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

这是第一个标签片段的代码

 public class SymptomsTabFragment extends Fragment {

@Bind(R.id.recycler_view_notificationsSymptoms)
RecyclerView mRecyclerView_notificationSymptoms;


NetworkStatus mNetworkStatus = null;

static AlertDialog mShowDialog = null;

Button mButton_right;

ArrayList<NotificationSymptomdata> notificationSymptoms = null;
ArrayList<NotificationSymptomdata> notificationSymptomid = null;
ArrayList<String> notificationSettingID = null;
ArrayList<NotificationSymptomdata> isNotification = null;


public SymptomsTabFragment() {
    // Required empty public constructor
}


public static SymptomsTabFragment newInstance() {
    SymptomsTabFragment fragment = new SymptomsTabFragment();
    Bundle args = new Bundle();
    fragment.setArguments(args);
    return fragment;
}

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    Log.e("stb", "oncreate");
}

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

    mButton_right = (Button) getActivity().findViewById(R.id.Button_right);


    Log.e("stb", "oncreateview");


    Toolbar.LayoutParams params = new Toolbar.LayoutParams(marginInDp(80), marginInDp(50));
    params.gravity = Gravity.RIGHT;
    params.setMargins(0, 0, marginInDp(20), 0);
    mButton_right.setLayoutParams(params);
    mButton_right.setBackgroundResource(0);
    mButton_right.setTag(1);
    mButton_right.setVisibility(View.VISIBLE);
    mButton_right.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            final int status = (Integer) v.getTag();
            if (status == 1) {
                mButton_right.setText("Select All");
                v.setTag(0);

            } else {

                mButton_right.setText("DeSelect All");
                v.setTag(1);
            }

            if (mButton_right.getText().toString().equalsIgnoreCase("Select All")) {


                ArrayList<UpdateNotificationRequestData> Updatenoti;

                Log.e("stb", "onclick");

                UpdateNotificationsRequestModel requestModel = new UpdateNotificationsRequestModel();
                requestModel.setUserID(AppPreferences.readString(getActivity(), AppPreferenceNames.sUserid, ""));
                requestModel.setAppVersion(CommonUtils.APP_VERSION);
                requestModel.setDeviceInfo(CommonUtils.DeviceInfo);
                requestModel.setDeviceTypeID(CommonUtils.DEVICE_TYPE_ID);

                Updatenoti = new ArrayList<UpdateNotificationRequestData>();
                UpdateNotificationRequestData requestData;
                for (int i = 0; i < notificationSymptoms.size(); i++) {
                    requestData = new UpdateNotificationRequestData();
                    requestData.setIsNotification("1");
                    requestData.setNotificationSettingID(notificationSymptoms.get(i).getNotificationSettingID());
                    Updatenoti.add(requestData);
                }

                requestModel.setUpdateNotification(Updatenoti);

                if (mNetworkStatus.isNetWorkAvailable(getActivity()) == true) {
                    update_notifications(requestModel);

                } else {
                    CommonUtils.showAlertDialog(getActivity(), "No Network Available. Please connect to network");
                }

            } else if (mButton_right.getText().toString().equalsIgnoreCase("DeSelect All")) {

                ArrayList<UpdateNotificationRequestData> Updatenoti;

                Log.e("stb", "onclick");

                UpdateNotificationsRequestModel requestModel = new UpdateNotificationsRequestModel();
                requestModel.setUserID(AppPreferences.readString(getActivity(), AppPreferenceNames.sUserid, ""));
                requestModel.setAppVersion(CommonUtils.APP_VERSION);
                requestModel.setDeviceInfo(CommonUtils.DeviceInfo);
                requestModel.setDeviceTypeID(CommonUtils.DEVICE_TYPE_ID);

                Updatenoti = new ArrayList<UpdateNotificationRequestData>();
                UpdateNotificationRequestData requestData;
                for (int i = 0; i < notificationSymptoms.size(); i++) {
                    requestData = new UpdateNotificationRequestData();
                    requestData.setIsNotification("0");
                    requestData.setNotificationSettingID(notificationSymptoms.get(i).getNotificationSettingID());
                    Updatenoti.add(requestData);
                }

                requestModel.setUpdateNotification(Updatenoti);

                if (mNetworkStatus.isNetWorkAvailable(getActivity()) == true) {
                    update_notifications(requestModel);
                } else {
                    CommonUtils.showAlertDialog(getActivity(), "No Network Available. Please connect to network");
                }


            }


        }
    });


    notificationSymptoms = new ArrayList<>();
    notificationSymptomid = new ArrayList<>();
    notificationSettingID = new ArrayList<>();
    isNotification = new ArrayList<>();

    mNetworkStatus = new NetworkStatus(getActivity());


    // Inflate the layout for this fragment
    return rootView;
}


/**
 * Used to set margin value programmatically
 *
 * @param sizeInDP
 * @return
 */
private int marginInDp(int sizeInDP) {
    int marginInDp = (int) TypedValue.applyDimension(
            TypedValue.COMPLEX_UNIT_DIP, sizeInDP, getResources()
                    .getDisplayMetrics());
    return marginInDp;
}


/**
 * Update the notification settings
 */
public void update_notifications(UpdateNotificationsRequestModel object) {
    /**
     * Start the progress Bar.
     */
    CommonUtils.show_progressbar(getActivity());

    /**
     * call api
     */

    Call<UpdateNotificationsResponseModel> responsecall = VirusApplication.getRestClient().getAPIService().updateNotifications(object);
    responsecall.enqueue(new Callback<UpdateNotificationsResponseModel>() {
        @Override
        public void onResponse(Response<UpdateNotificationsResponseModel> response, Retrofit retrofit) {

            /**
             * Stop the progress Bar
             */
            CommonUtils.stop_progressbar();

            if (response.isSuccess()) {
                //Server Success
                UpdateNotificationsResponseModel responseModel = response.body();
                if (responseModel.getErrorCode().equalsIgnoreCase("0")) {
                    //Data Success
                    Log.e("nf", "data success");

                    CommonUtils.showAlertDialog(getActivity(), responseModel.getMessage());

                   // getNotificationSettings();


                } else {
                    CommonUtils.showAlertDialog(getActivity(), responseModel.getMessage());

                   // getNotificationSettings();


                }
            } else {

                CommonUtils.showAlertDialog(getActivity(), "Server Error");

               // getNotificationSettings();

            }

        }

        @Override
        public void onFailure(Throwable t) {

            /**
             * Stop the progress Bar
             */
            CommonUtils.stop_progressbar();


        }
    });


}

@Override
public void onResume() {
    super.onResume();

    Log.e("stb", "onresume");

  /*  r = new MyReceiver();
    LocalBroadcastManager.getInstance(getActivity()).registerReceiver(r,
            new IntentFilter("TAG_REFRESH"));
        */
       /**
      * Downloads mychildren details.
     */
       if (mNetworkStatus.isNetWorkAvailable(getActivity()) == true) {
          getNotificationSettings();
       } else {
         CommonUtils.showAlertDialog(getActivity(),                      getString(R.string.network_unavailable));
    }




}


/**
 * Get Notification Settings
 */
public void getNotificationSettings() {

    //hit the getnotifications API to fetch the notification details

    CommonUtils.show_progressbar(getActivity());

    /**
     * Calls WebAPI
     */

    Call<NotificationsModel> notificationsModelCall = VirusApplication.getRestClient().getAPIService().notifications(getNotificationsrequest());
    notificationsModelCall.enqueue(new Callback<NotificationsModel>() {
        @Override
        public void onResponse(Response<NotificationsModel> response, Retrofit retrofit) {

            /**
             * Stops the Progresss bar
             */
            CommonUtils.stop_progressbar();

            if (response.isSuccess()) {//Server Success

                NotificationsModel notificationsModel = response.body();
                if (notificationsModel.getErrorCode().equalsIgnoreCase("0")) {// Data Success

                    int i = 1;
                    for (NotificationSymptomdata nsymptomsData : notificationsModel.getNotificationSymptomdata()) {
                        notificationSymptoms.add(nsymptomsData);
                        //  aSymptomsID.add(symptomsData.getSymptomID());

                       /* if (edit_child_symptoms_id == symptomsData.getSymptomID()) {
                            illness_selection_position = i;
                        }*/

                        i++;
                    }


                    Log.e("noti", "Symptoms ArraySize-->" + notificationSymptoms.size());

                    if (notificationSymptoms.size() != 0) {
                        NotificationsAdapter notificationsAdapter = new NotificationsAdapter(getActivity(), notificationSymptoms);
                        mRecyclerView_notificationSymptoms.setAdapter(notificationsAdapter);
                        notificationsAdapter.notifyDataSetChanged();
                        LinearLayoutManager SymptomsLayoutManager = new LinearLayoutManager(getActivity());
                        mRecyclerView_notificationSymptoms.setLayoutManager(SymptomsLayoutManager);
                    }

                    for(int j=0;j<notificationSymptoms.size();j++)
                    {
                        if (notificationSymptoms.get(j).getIsNotification().equalsIgnoreCase("true"))
                        {
                            mButton_right.setText("DeSelect All");
                        }
                        else
                        if(notificationSymptoms.get(j).getIsNotification().equalsIgnoreCase("false"))
                        {
                            mButton_right.setText("Select All");
                        }
                        else
                        if (notificationSymptoms.get(j).getIsNotification().equalsIgnoreCase("true") || (notificationSymptoms.get(j).getIsNotification().equalsIgnoreCase("false")))
                        {
                            Log.e("ins","coming  here");

                            mButton_right.setText("Select All");
                        }
                    }


                } else { // Data Failure
    //                        CommonUtils.makeToast(AddLogActivity.this,      illnessCategory.getMessage());
                    /**
                     * Stops the Progresss bar
                     */
                    CommonUtils.stop_progressbar();
                    Log.e("noti", "data failure");
                }
            } else {// Server Failure
 //                    CommonUtils.makeToast(AddLogActivity.this, "Server Error");
                /**
                 * Stops the Progresss bar
                 */
                CommonUtils.stop_progressbar();
                Log.e("noti", "server failure");
            }
        }


        @Override
        public void onFailure(Throwable t) {

            /**
             * Stops the Progresss bar
             */
            CommonUtils.stop_progressbar();
            Log.e("noti", "retrofit failure");

        }
    });


}

/**
 * Request values to Get notifications.
 *
 * @return map object
 */
public Map<String, Object> getNotificationsrequest() {

    Map<String, Object> getChildrenValues = new HashMap<>();
    getChildrenValues.put("appVersion", CommonUtils.APP_VERSION);
    getChildrenValues.put("deviceTypeID", CommonUtils.DEVICE_TYPE_ID);
    getChildrenValues.put("deviceInfo", CommonUtils.DeviceInfo);
    getChildrenValues.put("userID", AppPreferences.readString(getActivity(), AppPreferenceNames.sUserid, ""));

    return getChildrenValues;

   }
 }

我在这里面临的问题是基于按钮的文本单击 mButton_right,即“全选”或“取消全选”我应该更新我的片段中的内容。选择相应按钮时对 Web 服务的调用在选项卡内正确发生。

但是每当更新后收到新数据时,我都无法用新传入的数据刷新选项卡片段。 我应该如何以及在哪里调用服务来获取更新的数据并在单击按钮时刷新选项卡片段?请帮忙!

【问题讨论】:

    标签: android-viewpager android-tablayout


    【解决方案1】:

    为了刷新TabLayout 中的Fragment 的数据,您应该创建一个函数,该函数将在您更改Fragment 时始终被调用,并且您可以刷新其中的数据。更多请看:

     // In activity 
     final Fragment currentFragment = getSupportFragmentManager().findFragmentById(R.id.frame_container);
            if (currentFragment instanceof MainTabFragment) {
                   ((MainTabFragment) currentFragment).doRefresh();
            }
    

    【讨论】:

      猜你喜欢
      • 2016-11-24
      • 1970-01-01
      • 2019-07-17
      • 2018-06-01
      • 1970-01-01
      • 2011-06-26
      • 2015-01-14
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多