Android ViewPager не может обновить вид во фрагменте в первый раз. Обновление после смахивания, но почему?

Я добавляю viewPager в SlidingTab, в ViewPager есть 7 фрагментов.

Вот код viewPager

private void setSlidingTab() {
    // Creating The ViewPagerAdapter and Passing Fragment Manager, Titles
    // for the Tabs and Number Of Tabs.
    adapter = new MyPagerAdapter(getSupportFragmentManager());

    // Assigning ViewPager View and setting the adapter
    pager = (ViewPager) findViewById(R.id.pager);
    pager.setAdapter(adapter);

    // Assigning the Sliding Tab Layout View
    tabs = (SlidingTabLayout) findViewById(R.id.tabs);
    tabs.setCustomTabView(R.layout.sliding_tab_custom, R.id.slidingTabtext,
            R.id.slidingTabimage);
    tabs.setDistributeEvenly(true); // To make the Tabs Fixed set this true,
                                    // This makes the tabs Space Evenly in
                                    // Available width

    // Setting Custom Color for the Scroll bar indicator of the Tab View
    tabs.setCustomTabColorizer(new SlidingTabLayout.TabColorizer() {
        @Override
        public int getIndicatorColor(int position) {
            return getResources().getColor(R.color.selectorBar);
        }
    });

    // Setting the ViewPager For the SlidingTabsLayout
    tabs.setViewPager(pager);
}

public class MyPagerAdapter extends FragmentStatePagerAdapter {

    public MyPagerAdapter(
            android.support.v4.app.FragmentManager fragmentManager) {
        super(fragmentManager);
    }

    @Override
    public CharSequence getPageTitle(int position) {
        return Titles[position];
    }

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

    @Override
    public Fragment getItem(int position) {
        switch (position) {
        case 0:
            HomeFragment homeFragment = HomeFragment.newInstance(position,
                    "" + getPageTitle(position));
            onVollyResponse = (VolleyResposeIntf) homeFragment;
            return homeFragment;
        case 1:

            return MyToneFragment.newInstance(
                    position, "" + getPageTitle(position));
        case 2:
            return BrowseFragment.newInstance(position, ""
                    + getPageTitle(position));

        case 3:
            return BrowseFragment.newInstance(position, ""
                    + getPageTitle(position));

        case 4:
            return BrowseFragment.newInstance(position, ""
                    + getPageTitle(position));

        case 5:
            return BrowseFragment.newInstance(position, ""
                    + getPageTitle(position));

        case 6:
            return BrowseFragment.newInstance(position, ""
                    + getPageTitle(position));

        default:
            break;
        }
        return null;

    }

    @Override
    public int getItemPosition(Object object) {
        if (object instanceof UpdateableFragment) {
            ((UpdateableFragment) object).update();
        }
        // don't return POSITION_NONE, avoid fragment recreation.
        return super.getItemPosition(object);
    }
}

Первый фрагмент также получает данные с сервера, используя залп. В моем первом фрагменте также есть представление списка, но представление фрагмента не может быть обновлено в первый раз.

Вот фрагмент кода

    homeListView = (ListView) v.findViewById(R.id.homeListView);
    CategoryHolder.removeCategoryList();
    getAllCategory();

    // Add header
    View headerView = ((LayoutInflater) context
            .getSystemService(Context.LAYOUT_INFLATER_SERVICE)).inflate(
            R.layout.home_list_header, homeListView, false);
    adImageView = (ImageView) headerView.findViewById(R.id.adImageView);
    homeListView.addHeaderView(headerView, null, false);

public void getAllCategory() {
    // TODO Auto-generated method stub

    HashMap<String, String> mMap = new HashMap<String, String>();
    mMap.put("userID", userId);
    mMap.put("securityCode", AppConstants.SECURITY_CODE);
    String finalWebURL = AppConstants.BASE_URL + AppConstants.CATEGORY_LIST;
    homeActivity.callVolley(context, AppConstants.POST,
            AppConstants.CATEGORY_LIST, finalWebURL, mMap,
            AppConstants.CALL_TIME_OUT_LONG, false,
            AppConstants.VOLLEY_RETRY_COUNT, true, false, homeActivity);
}

private void setAllCategory(JSONObject jsonObject) {
    try {
        JSONArray jsonArray = jsonObject.getJSONArray("results");
        Category category;
        CategoryHolder categoryHolder = new CategoryHolder();

        for (int i = 0; i < jsonArray.length(); i++) {
            JSONObject categoryJsonObject = jsonArray.getJSONObject(i);

            category = new Category();
            // category.setId(categoryJsonObject.getString("countryID"));
            category.setEnglishName(categoryJsonObject
                    .getString("englishName"));
            category.setArabicName(categoryJsonObject
                    .getString("arabicName"));
            category.setImageUrl(categoryJsonObject.getString("image"));

            categoryHolder.setCategory(category);
            category = null;
        }
    } catch (JSONException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    adapter = new CategoryAdapter(mContext, homeActivity);
    homeListView.setAdapter(adapter);
    adapter.notifyDataSetChanged();

}

public class CategoryAdapter extends BaseAdapter {

private Context context;
private Vector<Category> categoryItems;
private int index = 0;
private HomeActivity activity;

public CategoryAdapter(Context context, HomeActivity activity) {
    this.activity = activity;
    this.context = context;
    this.categoryItems = CategoryHolder.getAllCategory();
}

@Override
public int getCount() {
    int size = categoryItems.size();
    if (size % 2 == 0)
        return Math.round(categoryItems.size() / 2);
    else {
        float value = Float.parseFloat("" + categoryItems.size());
        value = value / 2;
        return (Math.round(value));
    }
}

@Override
public Object getItem(int position) {
    return categoryItems.get(position);
}

@Override
public long getItemId(int position) {
    return position;
}

@Override
public View getView(int position, View convertView, ViewGroup parent) {

    ViewHolder holder = null;

    if (convertView == null) {
        LayoutInflater mInflater = (LayoutInflater) context
                .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        convertView = mInflater.inflate(R.layout.home_grid_item, parent,
                false);

        holder = new ViewHolder();
        holder.imgPerformer = (CircularImageView) convertView
                .findViewById(R.id.imgPerformer);
        holder.listItemTextView = (TextView) convertView
                .findViewById(R.id.listItemTextView);
        holder.imgPerformer1 = (CircularImageView) convertView
                .findViewById(R.id.imgPerformer1);
        holder.listItemTextView1 = (TextView) convertView
                .findViewById(R.id.listItemTextView1);
        holder.performerFirstLi = (LinearLayout) convertView
                .findViewById(R.id.performerFirstLi);
        holder.performerSecondLi = (LinearLayout) convertView
                .findViewById(R.id.performerSecondLi);

        convertView.setTag(holder);

    } else {
        holder = (ViewHolder) convertView.getTag();
    }

    index = position * 2;
    // holder.imgPerformer
    // .setImageResource(categoryItems.get(index).getImageUrl());
    Picasso.with(activity).load(categoryItems.get(index).getImageUrl())
            .placeholder(R.drawable.ic_launcher)
            .error(R.drawable.ic_launcher).transform(new RoundTransform())
            .into(holder.imgPerformer);
    holder.listItemTextView.setText(categoryItems.get(index)
            .getEnglishName());
    if (categoryItems.size() > index + 1) {
        holder.performerSecondLi.setVisibility(View.VISIBLE);
        // holder.imgPerformer1.setImageResource(categoryItems.get(index +
        // 1)
        // .getImageUrl());
        Picasso.with(activity)
                .load(categoryItems.get(index + 1).getImageUrl())
                .placeholder(R.drawable.ic_launcher)
                .error(R.drawable.ic_launcher)
                .transform(new RoundTransform()).into(holder.imgPerformer1);
        holder.listItemTextView1.setText(categoryItems.get(index + 1)
                .getEnglishName());
    } else {
        holder.performerSecondLi.setVisibility(View.INVISIBLE);
    }

    holder.imgPerformer.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
        }
    });
    holder.imgPerformer1.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
        }
    });

    return convertView;
}

private static class ViewHolder {
    public CircularImageView imgPerformer;
    public TextView listItemTextView;
    public CircularImageView imgPerformer1;
    public TextView listItemTextView1;
    public LinearLayout performerFirstLi;
    public LinearLayout performerSecondLi;
}}

Но после прокрутки вкладки и возврата к первому фрагменту, фрагмент получает данные с сервера и обновляет представление. Но мне нужно сначала и каждый раз, когда данные будут отображаться.

Я думаю, что в моем коде есть какая-то ошибка, но я не могу ее понять.

Нужна помощь.

0 ответов

Другие вопросы по тегам