我已经问过一个有关我的问题的问题,但是我没有得到任何适当的解决方案,因此我在此处添加了所有详细信息。
在我的活动中,有TabLayout和viewpager。创建活动时,它从服务器获取数据,并从该数据中动态添加选项卡。我对每个选项卡使用单个片段,以便将与每个选项卡相对应的数据填充到片段的列表视图中,该片段将显示在选项卡布局下方的视图分页器中。直接单击选项卡布局标题时,数据会更改正确地。但是,当滑动viewpager时,它可以工作,但是在选项卡标题更改后的一小段时间内,列表视图中显示的数据将是先前的选项卡标题。它仅持续一秒钟,但是会创建一个糟糕的用户体验。
我的活动
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_browse_tab);
sharedPreferences = this.getSharedPreferences(GlobalDeclarations.MY_PREFERENCE, Context.MODE_PRIVATE);
user_type = sharedPreferences.getString("user_type",null);
ab = getSupportActionBar();
ab.setHomeButtonEnabled(true);
ab.setDisplayHomeAsUpEnabled(true);
ab.setBackgroundDrawable(new ColorDrawable(Color.parseColor("#009FE3")));
ab.setTitle("Plans");
cd = new ConnectionDetector(this);
Intent intent = getIntent();
key_circle = intent.getStringExtra("key_circle");
value_circle = intent.getStringExtra("value_circle");
key_operator = intent.getStringExtra("key_operator");
value_operator = intent.getStringExtra("value_operator");
isMobile = intent.getBooleanExtra("isMobile", false);
if (isMobile) {
spinnerArray = getResources().getStringArray(R.array.recharge_plan_types);
plan_type = "1";
}
else {
spinnerArray = getResources().getStringArray(R.array.dth_plan_types);
plan_type = "1";
}
loadData();
mViewPager= (ViewPager)findViewById(R.id.viewpager);
mViewPager.setOffscreenPageLimit(1);
mTabLayout= (TabLayout)findViewById(R.id.tabs2);
mTabLayout.setSelectedTabIndicatorColor(Color.parseColor("#FF0000"));
mTabLayout.setSelectedTabIndicatorHeight((int) (5 * getResources().getDisplayMetrics().density));
mTabLayout.setTabTextColors(Color.parseColor("#727272"), Color.parseColor("#FF0000"));
mViewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(mTabLayout));
mTabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
@Override
public void onTabSelected(TabLayout.Tab tab) {
planList.clear();
mViewPager.setCurrentItem(tab.getPosition());
numTab = tab.getPosition();
plan_type = String.valueOf(numTab+1);
BrowsePlanModel model;
key = mylist.get(numTab);
try {
jsonArray = jsonObject.getJSONArray(key);
for (int i = 0; i < jsonArray.length(); i++) {
jsonObject2 = jsonArray.getJSONObject(i);
model = new BrowsePlanModel();
model.setTalkTime(jsonObject2.optString("talktime"));
model.setValidity(jsonObject2.optString("validity"));
model.setAmount(jsonObject2.optString("amount"));
model.setDescription(jsonObject2.optString("description"));
planList.add(model);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
@Override
public void onTabUnselected(TabLayout.Tab tab) {
}
@Override
public void onTabReselected(TabLayout.Tab tab) {
}
});
}
public ArrayList<BrowsePlanModel> getPlans(){
return planList;
}
@Override
public void onFragmentInteraction(Uri uri) {
}
private void setupViewPager(ViewPager mViewPager,String name) {
adapter.addFragment(new PlasFragment(), name);
mTabLayout.setSelectedTabIndicatorColor(Color.parseColor("#ff0000"));
}
public String getKey_circle() {
return key_circle;
}
public String getValue_circle(){
return value_circle;
}
public String getKey_operator() {
return key_operator;
}
public String getValue_operator(){
return value_operator;
}
public boolean getIsMobile(){
return isMobile;
}
public String getPlan(){
return plan_type;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
Intent intent = new Intent();
setResult(RESULT_OK, intent);
finish();
default:
return super.onOptionsItemSelected(item);
}
}
class ViewPagerAdapter extends FragmentStatePagerAdapter {
private final List<Fragment> mFragmentList = new ArrayList<>();
private final List<String> mFragmentTitleList = new ArrayList<>();
public ViewPagerAdapter(FragmentManager manager) {
super(manager);
}
@Override
public Fragment getItem(int position) {
return new PlasFragment().newInstance(position);
}
@Override
public int getItemPosition(Object object) {
return POSITION_NONE;
}
@Override
public int getCount() {
return mFragmentList.size();
}
public void addFragment(Fragment fragment, String title) {
mFragmentList.add(fragment);
mFragmentTitleList.add(title);
}
@Override
public CharSequence getPageTitle(int position) {
return mFragmentTitleList.get(position);
}
}
private void loadData() {
String url = null;
HashMap<String, String> data = new HashMap<>();
data.put("plan", plan_type);
data.put("operator", key_operator);
data.put("circle", key_circle);
if(cd.isConnectingToInternet()) {
if (isMobile) {
url = GlobalDeclarations.URL1;
} else {
url = GlobalDeclarations.URL2;
}
new HTTPRequest(BrowseTabActivity.this, data, null, HTTPRequest.METHOD.GET, BrowseTabActivity.this).execute(url);
}
else{
Toast.makeText(this, "No Internet Connection", Toast.LENGTH_SHORT).show();
}
}
@Override
public void onConnectionStarted() {
}
@Override
public void onConnectionFailed() {
}
@Override
public void onCompleted(JSONObject resultData) {
planList = new ArrayList<>();
mylist = new ArrayList<String>();
BrowsePlanModel model;
if (resultData.has("status")) {
String status = resultData.optString("status");
if (status.equalsIgnoreCase("failed")) {
Toast.makeText(this, resultData.optString("status"), Toast.LENGTH_SHORT).show();
}
else if (status.equalsIgnoreCase("success")) {
try {
jsonObject = resultData.getJSONObject("data");
planList.clear();
adapter = new ViewPagerAdapter(getSupportFragmentManager());
for(Iterator<String> iter = jsonObject.keys();iter.hasNext();) {
key = iter.next();
mylist.add(key);
mTabLayout.addTab(mTabLayout.newTab().setText(key));
mTabLayout.setTabMode(TabLayout.MODE_SCROLLABLE);
setupViewPager(mViewPager,key);
}
mViewPager.setAdapter(adapter);
} catch (Exception e) {
e.printStackTrace();
planList.clear();
}
}
}
}
}
“我的片段”用于填充列表视图
public class PlasFragment extends Fragment implements HTTPCallback {
private static final String ARG_PARAM1 = "param1";
private static final String ARG_PARAM2 = "param2";
private String mParam1;
private String mParam2;
private Spinner spinner_plan_type;
private ListView listView;
private TextView textToast;
private String key_circle;
private String value_circle;
private String key_operator;
private String value_operator;
private String plan_type;
android.support.v7.app.ActionBar ab;
private boolean isMobile;
private SharedPreferences sharedPreferences;
private String userId;
private String apiKey;
private ArrayList<BrowsePlanModel> planList;
private BrowsePlanAdapter adapter ;
private String[] spinnerArray;
ProgressBar prgs;
private BroadcastReceiver mRegistrationBroadcastReceiver;
private android.support.v4.app.NavUtils NavUtils;
MediaPlayer mp;
String table_id;
Integer selected_radio_button;
String wallet_request,type;
JSONObject jsonResult;
ConnectionDetector cd;
View rootview;
private OnFragmentInteractionListener mListener;
public PlasFragment() {
}
public static PlasFragment newInstance(String param1, String param2) {
PlasFragment fragment = new PlasFragment();
Bundle args = new Bundle();
args.putString(ARG_PARAM1, param1);
args.putString(ARG_PARAM2, param2);
fragment.setArguments(args);
return fragment;
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
mParam1 = getArguments().getString(ARG_PARAM1);
mParam2 = getArguments().getString(ARG_PARAM2);
}
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
rootview = inflater.inflate(R.layout.fragment_plas, container, false);
cd = new ConnectionDetector(getContext());
prgs = (ProgressBar)rootview.findViewById(R.id.progressBar1);
listView = (ListView)rootview.findViewById(R.id.list_plan_type);
textToast = (TextView)rootview.findViewById(R.id.text_toast);
key_circle = ((BrowseTabActivity)getActivity()).getKey_circle();
value_circle = ((BrowseTabActivity)getActivity()).getValue_circle();
key_operator = ((BrowseTabActivity)getActivity()).getKey_operator();
value_operator =((BrowseTabActivity)getActivity()).getValue_operator();
isMobile = ((BrowseTabActivity)getActivity()).getIsMobile();
plan_type = ((BrowseTabActivity)getActivity()).getPlan();
loadData();
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
BrowsePlanModel browsePlan = (BrowsePlanModel) parent.getItemAtPosition(position);
Intent intent = new Intent();
intent.putExtra("amount", browsePlan.getAmount());
getActivity().setResult(Activity.RESULT_OK,intent);
getActivity().finish();
}
});
return rootview;
}
public void onButtonPressed(Uri uri) {
if (mListener != null) {
mListener.onFragmentInteraction(uri);
}
}
public interface OnFragmentInteractionListener {
void onFragmentInteraction(Uri uri);
}
private void loadData() {
BrowsePlanModel browsePlan;
textToast.setVisibility(View.GONE);
listView.setVisibility(View.VISIBLE);
planList = ((BrowseTabActivity)getActivity()).getPlans();
setAdapter();
}
@Override
public void onConnectionStarted() {
}
@Override
public void onConnectionFailed() {
}
@Override
public void onCompleted(JSONObject resultData) {
planList = new ArrayList<>();
JSONArray jsonArray;
JSONObject jsonObject;
BrowsePlanModel model;
if (resultData.has("status")) {
String status = resultData.optString("status");
if (status.equalsIgnoreCase("failed")) {
prgs.setVisibility(View.GONE);
textToast.setVisibility(View.VISIBLE);
listView.setVisibility(View.GONE);
Toast.makeText(getContext(), resultData.optString("status"), Toast.LENGTH_SHORT).show();
}
else if (status.equalsIgnoreCase("success")) {
try {
jsonArray = resultData.getJSONArray("data");
if (jsonArray.length() > 0 && jsonArray != null) {
for (int i = 0; i < jsonArray.length(); i++) {
jsonObject = jsonArray.getJSONObject(i);
model = new BrowsePlanModel();
model.setTalkTime(jsonObject.optString("talktime"));
model.setValidity(jsonObject.optString("validity"));
model.setAmount(jsonObject.optString("amount"));
model.setDescription(jsonObject.optString("description"));
planList.add(model);
}
textToast.setVisibility(View.GONE);
listView.setVisibility(View.VISIBLE);
setAdapter();
} else {
planList.clear();
setAdapter();
textToast.setVisibility(View.VISIBLE);
listView.setVisibility(View.GONE);
}
prgs.setVisibility(View.GONE);
} catch (Exception e) {
e.printStackTrace();
planList.clear();
setAdapter();
textToast.setVisibility(View.VISIBLE);
listView.setVisibility(View.GONE);
}
}
}
}
private void setAdapter() {
try {
adapter = new BrowsePlanAdapter(getContext(), planList);
listView.setAdapter(adapter);
Collections.sort(planList);
prgs.setVisibility(View.GONE);
}catch (Exception e){
}
}
@Override
public void setUserVisibleHint(boolean isVisibleToUser) {
super.setUserVisibleHint(isVisibleToUser);
if (isVisibleToUser) {
getFragmentManager().beginTransaction().detach(this).attach(this).commit();
}
}
}
通过在Viewpager上滑动来更改选项卡时,会发生此错误,即第一个选项卡包含充值数据,第二个选项卡包含完整通话时间。但滑动以更改标签时,前一标签的数据会显示一小段时间。但是,当我通过直接选择选项卡来更改选项卡时,不会出现此错误,仅当在viewpager上滑动时才会发生。我已经在这个问题上坚持了很长时间,请提出一个解决方案。