RecyclerView投掷并移动不顺畅

时间:2015-11-19 09:03:04

标签: android android-recyclerview

我是中国的编码员。我不擅长英语,所以请尽量描述这个问题。非常感谢你的回答。

当我第一次使用RecyclerView进行活动并滚动时,它并不顺畅,尤其是下一个项目,但是当我滚动Recyclerview时,它是可行的,并且流畅。一些程序员说我们无法在onCreateViewHolder()和onBindViewHolder()上做太多工作,但我无法得到它。

这是我的代码:

片段

public class HomeFragment extends RefreshableFragment implements IHomeView {

    @Bind(R.id.refresh_view)
    PullToRefreshRecyclerView refresh_view;

    private RecyclerView refreshableView;
    private HomePresenter homePresenter;

    @Override
    public View initSuccessView() {
        View view = View.inflate(getContext(), R.layout.fragment_refreshable_success_recyclerview, null);
        ButterKnife.bind(this, view);
        initRefreshLayout();
        initRecyclerView();
        return view;
    }

    /**
     * 初始化可刷新控件
     */
    private void initRefreshLayout() {
        refresh_view.setMode(PullToRefreshBase.Mode.BOTH);
        refresh_view.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener2<RecyclerView>() {
            @Override
            public void onPullDownToRefresh(PullToRefreshBase<RecyclerView> refreshView) {
                homePresenter.refresh();
            }

            @Override
            public void onPullUpToRefresh(PullToRefreshBase<RecyclerView> refreshView) {
                homePresenter.loadMore();
            }
        });
    }

    /**
     * 初始化RecyclerView控件
     */
    private void initRecyclerView() {
        refreshableView = refresh_view.getRefreshableView();
        RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(getContext(),LinearLayoutManager.VERTICAL,false);
        SpaceItemDecoration decor = new SpaceItemDecoration(2);
        refreshableView.addItemDecoration(decor);
        refreshableView.setLayoutManager(layoutManager);
        refreshableView.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
                int childCount = recyclerView.getChildCount();
                for (int i = 0; i < childCount; i++) {
                    View view = recyclerView.getChildAt(i);
                    RecyclerView.ViewHolder holder = recyclerView.getChildViewHolder(view);
                    switch (holder.getItemViewType()){
                        case HomeAdapter.TYPE_TOPIC:
                            HomeTopicViewHolder topicViewHolder = (HomeTopicViewHolder) holder;
                            topicViewHolder.setParentHeight(recyclerView.getHeight());
                            topicViewHolder.setOffset();
                    }
                }
            }
        });
    }

    @Override
    protected void requestNetwork() {
        homePresenter = new HomePresenter(getContext(),this,null);
        homePresenter.init();
    }

    @Override
    public RecyclerView getRecyclerView() {
        return refreshableView;
    }

    @Override
    public RefreshView getRefreshView() {
        return getParentRefreshView();
    }

    @Override
    public void onRefreshFinish() {
        if(refresh_view.isRefreshing()){
            refresh_view.onRefreshComplete();
        }
    }

    @Override
    public void onLordMoreFinish() {

    }

}


呈现

public class HomePresenter extends BasePresenter<IHomeView> implements IHomePresenter, StringLoaderCallback {

    private Gson gson;
    private HomeAdapter homeAdapter;
    private final Pagination pagination;

    public HomePresenter(Context context,IHomeView homeView,Bundle bundle) {
        super(context,homeView,bundle);
        gson = new Gson();
        homeAdapter = new HomeAdapter();
        getPresenterView().getRecyclerView().setAdapter(homeAdapter);

        pagination = new Pagination();
        pagination.setLimit(10);
        pagination.setOffset(0);
    }

    @Override
    public void init() {
        String bannerUrl = ServerAPI.Home.buildHomeBannerUrl();
        NetworkStringLoader.getInstance(context).sendGetStringRequest(bannerUrl, null, bannerUrl, this);
        String topicUrl = ServerAPI.Home.buildHomeTopicUrl();
        NetworkStringLoader.getInstance(context).sendGetStringRequest(topicUrl, null, topicUrl, this);
        String routeUrl = ServerAPI.Home.buildHomeRouteUrl();
        NetworkStringLoader.getInstance(context).sendGetStringRequest(routeUrl, pagination.getMap(), REFRESH, this);
    }

    @Override
    public void loadMore() {
        String routeUrl = ServerAPI.Home.buildHomeRouteUrl();
        pagination.setOffset(pagination.getTotal());
        pagination.setLimit(10);
        NetworkStringLoader.getInstance(context).sendGetStringRequest(routeUrl, pagination.getMap(), LOADMORE, this);
    }

    @Override
    public void refresh() {
        pagination.setOffset(0);
        pagination.setLimit(10);
        pagination.clearTotal();
        init();
    }

    @Override
    public void onLoadFinished(String url,Map<String,String> params, String data,Object tag) {
        if(url.equals(ServerAPI.Home.buildHomeBannerUrl())){
            Log.i(url,data);
            HomeBanner.HomeBannerLists homeBannerLists = gson.fromJson(data,HomeBanner.HomeBannerLists.class);
            homeAdapter.setBanners(homeBannerLists.list);
        }
        if(url.equals(ServerAPI.Home.buildHomeTopicUrl())){
            Log.i(url,data);
            HomeTopic.HomeTopicLists homeTopicLists = gson.fromJson(data,HomeTopic.HomeTopicLists.class);
            homeAdapter.setTopics(homeTopicLists.list);
        }
        if(url.equals(ServerAPI.Home.buildHomeRouteUrl())){
            Log.i(url,data);
            int mode = (int) tag;
            HomeRoute.HomeRouteLists homeRouteLists = gson.fromJson(data, HomeRoute.HomeRouteLists.class);
            if (mode == REFRESH){
                homeAdapter.setRoutes(homeRouteLists.list);
            } else if(mode == LOADMORE){
                homeAdapter.appendRoutes(homeRouteLists.list);
            }
            pagination.appendTotal(homeRouteLists.list.size());

        }
        getPresenterView().getRefreshView().setCurrentState(RefreshView.STATE_SUCCESS);
        getPresenterView().onRefreshFinish();
    }

    @Override
    public void onLoadError(VolleyError error) {
        Log.i("error",error.getMessage());
    }
}

适配器

public class HomeAdapter extends RecyclerView.Adapter {

    public static final int TYPE_BANNER = 0;
    public static final int TYPE_TOPIC = 1;
    public static final int TYPE_ROUTE = 2;

    private List<HomeBanner> banners = new ArrayList<>();
    private List<HomeTopic> topics = new ArrayList<>();
    private List<HomeRoute> routes = new ArrayList<>();

    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        switch (viewType){
            case TYPE_BANNER:
                View bannerView = HomeBannerViewHolder.getView(parent.getContext());
                return new HomeBannerViewHolder(bannerView);
            case TYPE_TOPIC:
                View topicView = View.inflate(parent.getContext(), R.layout.item_home_topic,null);
//                View topicView = HomeTopicViewHolder.getView(parent.getContext());
                return new HomeTopicViewHolder(topicView);
            case TYPE_ROUTE:
                View routeView = View.inflate(parent.getContext(), R.layout.item_home_route,null);
//                View routeView = HomeRouteViewHolder.getView(parent.getContext());
                return new HomeRouteViewHolder(routeView);
            default:
//                View defaultView = new View(parent.getContext());
                View view = EmptyViewHolder.getView(parent.getContext());
                return new EmptyViewHolder(view);
        }
    }

    @Override
    public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
        if(position == 0){
            onBindBannerViewHolder(holder);
        }else if(position>0 && position<topics.size()+1){
            onBindTopicViewHolder(holder,position-1);
        }else {
            onBindRouteViewHolder(holder,position-topics.size()-1);
        }

    }

    private void onBindRouteViewHolder(RecyclerView.ViewHolder holder, int position) {
        HomeRouteViewHolder routeViewHolder = (HomeRouteViewHolder) holder;
        routeViewHolder.setData(routes.get(position));
    }

    private void onBindTopicViewHolder(RecyclerView.ViewHolder holder,int position) {
        HomeTopicViewHolder topicViewHolder = (HomeTopicViewHolder) holder;
        topicViewHolder.setData(topics.get(position));
    }

    private void onBindBannerViewHolder(RecyclerView.ViewHolder holder) {
        HomeBannerViewHolder bannerViewHolder = (HomeBannerViewHolder) holder;
        bannerViewHolder.setData(banners);
    }

    @Override
    public int getItemCount() {
        return 1 + topics.size()+routes.size();
    }

    @Override
    public int getItemViewType(int position) {
        if(position == 0){
            return TYPE_BANNER;
        }else if(position<topics.size()+1){
            return TYPE_TOPIC;
        }else {
            return TYPE_ROUTE;
        }
    }

    public void setBanners(List<HomeBanner> list){
        banners.clear();
        banners.addAll(list);
        notifyDataSetChanged();
    }

    public void setTopics(List<HomeTopic> list) {
        topics.clear();
        topics.addAll(list);
        notifyDataSetChanged();
    }

    public void setRoutes(List<HomeRoute> list) {
        routes.clear();
        routes.addAll(list);
        notifyDataSetChanged();
    }

    public void appendRoutes(List<HomeRoute> list) {
        routes.addAll(routes.size(),list);
        notifyItemRangeInserted(getItemCount(),list.size());
    }
}


保持器

public class HomeTopicViewHolder extends BaseViewHolder<HomeTopic> {

    private static SimpleDraweeView content_iv ;
    private static TextView home_topic_title ;
    private static TextView home_topic_discription ;

    private int height;

    public static View getView(Context context) {
        View topicView = View.inflate(context, R.layout.item_home_topic,null);
        return topicView;
    }

    public HomeTopicViewHolder(View itemView) {
        super(itemView);
        content_iv = (SimpleDraweeView) itemView.findViewById(R.id.home_topic_iv);
        if(content_iv!=null){
            content_iv = (SimpleDraweeView) itemView.findViewById(R.id.home_topic_iv);
        }
        if(home_topic_title!=null){
            home_topic_title = (TextView) itemView.findViewById(R.id.home_topic_title);
        }
        if(home_topic_discription!=null){
            home_topic_discription = (TextView) itemView.findViewById(R.id.home_topic_discription);
        }
        if(height==0){
            SharedPreferences sp = SharedPreferenceHelper.getInstance().getSharedPreference(itemView.getContext(), SharedPreferenceHelper.EnumSPName.CONFIG);
            int scale = sp.getInt(SharedPreferenceHelper.EnumSPName.windowWidth, 0);
            FrameLayout.LayoutParams layoutParams = new FrameLayout.LayoutParams(scale,scale);
            content_iv.setLayoutParams(layoutParams);
        }
    }

    @Override
    protected void inflateView(HomeTopic data) {
        NetworkImageLoader loader = NetworkImageLoader.getInstance();
        loader.setUrlToSimpleDraweeView(data.getImage(),content_iv);
        home_topic_title.setText(data.getName());
        home_topic_discription.setText(String.format(getResources().getString(R.string.guider_route),data.getGuide(), data.getRoute()));

    }

    public void setOffset() {
        int itemViewHeight = itemView.getHeight();
        int imageViewHeight = content_iv.getHeight();

        int parentOffsetMax = (getParentHeight() + itemViewHeight) / 2;
        int offsetMax = imageViewHeight - itemViewHeight;

        float y = itemView.getY();
        float location = y + itemViewHeight/2;
        float v = location - getParentHeight() / 2;

        float percent = v/parentOffsetMax;

        int margin = (int) ((offsetMax/2)*(percent + 1));

        FrameLayout.LayoutParams layoutParams = (FrameLayout.LayoutParams) content_iv.getLayoutParams();
        layoutParams.setMargins(0,-margin,0,0);
        content_iv.setLayoutParams(layoutParams);
    }

    public void setParentHeight(int height) {
        this.height = height;
    }
    public int getParentHeight() {
        return height;
    }
}

0 个答案:

没有答案