如何在片段之间一个选项卡与另一个选项卡之间切换时动态刷新选项卡内容? [英] How to refresh tabs content dynamically while switching between one tab to other in fragment?

查看:75
本文介绍了如何在片段之间一个选项卡与另一个选项卡之间切换时动态刷新选项卡内容?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个名为CourseActivity.java的Activity,其中我有2个选项卡,分别名为UserCourses和FavouriteCourses.我在第一个选项卡中有一些课程列表.它带有图标,在选择图标te时,相应的粗体将添加到Favouritecourse列表中.但是我的问题是,当我转到收藏夹课程"选项卡时,直到刷新或注销并再次登录到应用程序后,内容才会更新.

I have Activity called CourseActivity.java,in that i have 2 tabs by names UserCourses and FavouriteCourses.I have some list of courses in first tab.And it have icon,on selecting icon te respective coarse will be added to Favouritecourse list.But my problem is when i go to Favourite Course tab,the content will not update untill i refresh it or i logout and login again to app.

这里是CoarseActivity.java.这会将课程类型发送到CourseFragment.java

Here is CoarseActivity.java.This will send type of course to CourseFragment.java

//display content of tabs on touch of tabs
class CourseTabsAdapter extends FragmentStatePagerAdapter {


    public CourseTabsAdapter(FragmentManager fm)
    {
        super(fm);
    }

    @Override
    public Fragment getItem(int position) {
        /*
         * We use bundle to pass course listing type because, by using other
         * methods we will lose the listing type information in the fragment
         * on onResume (this calls empty constructor). For the same reason
         * interface may not work. Bundles are passed again on onResume
         */
        switch (position) {
        case 0:

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

            CourseFragment userCourses = new CourseFragment();

            // Set the listing type to only user courses in bundle.
            Bundle bundle = new Bundle();
            bundle.putInt("coursesType", CourseFragment.TYPE_USER_COURSES);
            userCourses.setArguments(bundle);

            return userCourses;
        case 1:
            CourseFragment favCourses = new CourseFragment();

            /*favCourses.onRefresh();*/

            /*new courseSyncerBg().execute("");*/
            // Set the listing type to only user courses in bundle.
            Bundle bundle1 = new Bundle();
            bundle1.putInt("coursesType", CourseFragment.TYPE_FAV_COURSES);
            favCourses.setArguments(bundle1);

            return favCourses;
        }
        return null;
    }

这是我的CourseFragment.java

And this is my CourseFragment.java

public class CourseFragment extends Fragment implements OnRefreshListener {
/**
 * List all courses in Moodle site
 */
public static final int TYPE_ALL_COURSES = 0;
/**
 * List only user courses
 */
public static final int TYPE_USER_COURSES = 1;
/**
 * List only courses favourited by user
 */
public static final int TYPE_FAV_COURSES = 2;

CourseListAdapter courseListAdapter;
SessionSetting session;
List<MoodleCourse> mCourses;
int Type = 0;
LinearLayout courseEmptyLayout;
SwipeRefreshLayout swipeLayout;

/**
 * Pass the course listing type as a bundle param of type int with name
 * coursesType
 */
public CourseFragment() {
}

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    if (this.getArguments() != null)
        Type = this.getArguments().getInt("coursesType", TYPE_USER_COURSES);
}

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

    View rootView = inflater.inflate(R.layout.frag_courses, container,
            false);

    // Get all courses of this site
    session = new SessionSetting(getActivity());

    if (Type == TYPE_USER_COURSES)
        mCourses = MoodleCourse.find(MoodleCourse.class,
                "siteid = ? and is_user_course = ?",
                session.getCurrentSiteId() + "", "1");
    else if (Type == TYPE_FAV_COURSES)
        mCourses = MoodleCourse.find(MoodleCourse.class,
                "siteid = ? and is_fav_course = ?",
                session.getCurrentSiteId() + "", "1");
    else
        mCourses = MoodleCourse.find(MoodleCourse.class, "siteid = ?",
                session.getCurrentSiteId() + "");

    courseEmptyLayout = (LinearLayout) rootView
            .findViewById(R.id.course_empty_layout);
    ListView courseList = (ListView) rootView
            .findViewById(R.id.content_course);
    courseListAdapter = new CourseListAdapter(getActivity());
    courseList.setAdapter(courseListAdapter);

    swipeLayout = (SwipeRefreshLayout) rootView
            .findViewById(R.id.swipe_refresh);
    Workaround.linkSwipeRefreshAndListView(swipeLayout, courseList);
    swipeLayout.setOnRefreshListener(this);

    // We don't want to run sync in each course listing
    if (Type == TYPE_USER_COURSES)
        new courseSyncerBg().execute("");

    return rootView;
}

public class CourseListAdapter extends BaseAdapter {
    private final Context context;

    public CourseListAdapter(Context context) {
        this.context = context;
        if (!mCourses.isEmpty())
            courseEmptyLayout.setVisibility(LinearLayout.GONE);
    }

    @Override
    public View getView(final int position, View convertView,
            ViewGroup parent) {
        final ViewHolder viewHolder;

        if (convertView == null) {
            viewHolder = new ViewHolder();
            LayoutInflater inflater = (LayoutInflater) context
                    .getSystemService(Context.LAYOUT_INFLATER_SERVICE);

            convertView = inflater.inflate(R.layout.list_item_course,
                    parent, false);

            viewHolder.shortname = (TextView) convertView
                    .findViewById(R.id.list_course_shortname);
            viewHolder.fullname = (TextView) convertView
                    .findViewById(R.id.list_course_fullname);
            viewHolder.favIcon = (ImageView) convertView
                    .findViewById(R.id.list_course_fav);

            // Save the holder with the view
            convertView.setTag(viewHolder);
        } else {
            // Just use the viewHolder and avoid findviewbyid()
            viewHolder = (ViewHolder) convertView.getTag();
        }

        // Assign values
        final MoodleCourse mCourse = mCourses.get(position);
        viewHolder.shortname.setText(mCourse.getShortname());
        viewHolder.fullname.setText(mCourse.getFullname());
        if (mCourses.get(position).getIsFavCourse())
            viewHolder.favIcon.setImageResource(R.drawable.icon_favorite);
        else
            viewHolder.favIcon
                    .setImageResource(R.drawable.icon_favorite_outline);

        convertView.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View arg0) {
                Intent i = new Intent(context, CourseContentActivity.class);
                i.putExtra("courseid", mCourses.get(position).getCourseid());
                context.startActivity(i);
            }
        });

        viewHolder.favIcon.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View arg0) {

                // Simply unfav if that's the case
                if (mCourse.getIsFavCourse()) {
                    mCourse.setIsFavCourse(!mCourse.getIsFavCourse());
                    mCourse.save();

                    // Update listview
                    mCourses.get(position).setIsFavCourse(
                            mCourse.getIsFavCourse());
                    courseListAdapter.notifyDataSetChanged();

                    // Update listview
                    mCourses.get(position).setIsFavCourse(
                            mCourse.getIsFavCourse());
                    courseListAdapter.notifyDataSetChanged();

                    return;
                }

                // If fav'ing, ask for confirmation. We will be doing a sync
                AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(
                        context);
                alertDialogBuilder
                        .setMessage("This will make course contents offline and sends notifications for new contents if enabled");
                alertDialogBuilder.setTitle("Add "
                        + mCourses.get(position).getShortname()
                        + " to favourites?");
                alertDialogBuilder.setPositiveButton("Yes",
                        new DialogInterface.OnClickListener() {

                            @Override
                            public void onClick(DialogInterface arg0,
                                    int arg1) {
                                mCourse.setIsFavCourse(!mCourse
                                        .getIsFavCourse());
                                mCourse.save();

                                // Update listview
                                mCourses.get(position).setIsFavCourse(
                                        mCourse.getIsFavCourse());
                                courseListAdapter.notifyDataSetChanged();

                                // Start sync service for course
                                Intent i = new Intent(context,
                                        MDroidService.class);
                                i.putExtra("notifications", false);
                                i.putExtra("siteid",
                                        session.getCurrentSiteId());
                                i.putExtra("courseid",
                                        mCourse.getCourseid());
                                context.startService(i);

                            }
                        });
                alertDialogBuilder.setNegativeButton("No",
                        new DialogInterface.OnClickListener() {

                            @Override
                            public void onClick(DialogInterface dialog,
                                    int which) {

                            }
                        });

                AlertDialog alertDialog = alertDialogBuilder.create();
                alertDialog.show();
            }
        });

        return convertView;
    }

    @Override
    public int getCount() {
        return mCourses.size();
    }

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

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

static class ViewHolder {
    TextView shortname;
    TextView fullname;
    ImageView favIcon;
}

/**
 * Syncs the courses of the current user in background and updates list *
 * 
 * @author Praveen Kumar Pendyala (praveen@praveenkumar.co.in)
 * 
 */
private class courseSyncerBg extends AsyncTask<String, Integer, Boolean> {

    @Override
    protected void onPreExecute() {
        swipeLayout.setRefreshing(true);
    }

    @Override
    protected Boolean doInBackground(String... params) {
        CourseSyncTask cs = new CourseSyncTask(session.getmUrl(),
                session.getToken(), session.getCurrentSiteId());
        return cs.syncUserCourses();
    }

    @Override
    protected void onPostExecute(Boolean result) {
        if (Type == TYPE_USER_COURSES)
            mCourses = MoodleCourse.find(MoodleCourse.class,
                    "siteid = ? and is_user_course = ?",
                    session.getCurrentSiteId() + "", "1");
        else if (Type == TYPE_FAV_COURSES)
            mCourses = MoodleCourse.find(MoodleCourse.class,
                    "siteid = ? and is_fav_course = ?",
                    session.getCurrentSiteId() + "", "1");
        else
            mCourses = MoodleCourse.find(MoodleCourse.class,
                    "siteid = ? and ", session.getCurrentSiteId() + "");
        courseListAdapter.notifyDataSetChanged();
        if (!mCourses.isEmpty())
            courseEmptyLayout.setVisibility(LinearLayout.GONE);
        swipeLayout.setRefreshing(false);
    }
}

@Override
public void onRefresh() {
    new courseSyncerBg().execute("");
}

}

请帮助我解决问题.我已经在下面提到了.但是我无法解决我的问题.

Please help me to sortout problem.I already refered below one.But i couldnt get answer to my problem.

http://stackoverflow.com/questions/10849552/update-viewpager-dynamically/17855730#17855730

http://stackoverflow.com/questions/10849552/update-viewpager-dynamically/17855730#17855730

推荐答案

您应该在片段中覆盖setUserVisibleHint方法并将刷新代码放入其中

you should override setUserVisibleHint method in your fragment and put your refreshing code in it

    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
    super.setUserVisibleHint(isVisibleToUser);
       if (isVisibleToUser && isResumed()) {

       }
    }

这篇关于如何在片段之间一个选项卡与另一个选项卡之间切换时动态刷新选项卡内容?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆