页面类型一:红框是个Fragment,头部是一张大图,下面都是为两列的图,用的是recyclerview实现
页面类型二:红框是个Fragment,头部是无线循环轮播,下面是栏目,用的是recyclerview实现
页面类型二:红框是个Fragment,头部是无线循环轮播,下面是两列图,用的是recyclerview实现
首页进来就是10个页面(viewpager+Fragment),滑动切换页面的时候低端机子会明显卡顿,配置好的手机,如果快速滑动切换也不是那么流畅
下面贴代码:
public class HomeContentItemFragment extends BaseFragment {
public static final String MODEL = "model";
public static final String TYPE = "type_show";
public static final String ISFIRSTPAGER = "isFirstPager";
// 安利电台
public final static int AUDIO_ID = 999999998; //点击“听见安利”的id
public final static int SUBJECT_ID = 7; //点击“主题专区”的id
private final int RECOMMEND_ID = 100;// navId=100为推荐id
private NavModel navModel;
private List<VideoModel> videoList;
private List<VideoModel> contentVideoList1,heardVideoList;
private List<HomeContentVideoInfo> contentVideoList2;
private ImageLoader imgImageLoader;
private ImageView empty;
private PtrClassicFrameLayout refreshLayout;
private int TYPE_SHOW;//0默认头部轮播页面,1为单张大图页面,-1为含有二三级页面
private RecyclerView recyclerView;
private ContentItemAdapter_recylerview adapter_recylerview;
public static HomeContentItemFragment newInstance(NavModel navModel,boolean isFirstPager,int TYPE_SHOW)
{
HomeContentItemFragment fragment = new HomeContentItemFragment();
Bundle bundle = new Bundle();
bundle.putSerializable(MODEL, navModel);
bundle.putBoolean(ISFIRSTPAGER, isFirstPager);
bundle.putInt(TYPE,TYPE_SHOW);
fragment.setArguments(bundle);
return fragment;
}
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
}
private boolean isLogin;
@Override
protected void initData()
{
videoList=new ArrayList<VideoModel>();
imgImageLoader = ImageLoader.getInstance();
navModel = getArguments() != null ? (NavModel) getArguments().getSerializable(MODEL) : null;
TYPE_SHOW=getArguments() != null ? getArguments().getInt(TYPE) : 0;
isLogin = !UserDBUtil.getInstance(getApplicationContext()).isNeedLogin();
}
private int navId;
public void initVideoList(){
if (navModel != null)
{
navId= (int) navModel.getNavId();
videoList.clear();
if (navModel.getNavId() == RECOMMEND_ID)
{
videoList = VideoDBUtil.getRecomendVideo(navModel.getNavId(), isLogin,getApplicationContext());
} else if (navModel.getNavId() == AUDIO_ID)
{
videoList = VideoDBUtil.getAudioVideo(isLogin,getApplicationContext());
} else if (navModel.getNavId() == SUBJECT_ID)
{
videoList = VideoDBUtil.getSubjectVideo(isLogin,getApplicationContext());
} else
{
videoList = VideoDBUtil.getCategoryVideo(navModel.getNavId(), isLogin,getApplicationContext());
}
}
if (videoList == null)
{
videoList = new ArrayList<VideoModel>();
}
//内容是显示类型1
if(TYPE_SHOW==0||TYPE_SHOW==1){
if(videoList!=null&&videoList.size()>0){
heardVideoList=new ArrayList<VideoModel>();
contentVideoList1=new ArrayList<VideoModel>();
for (int i=0;i<videoList.size();i++)
{
switch (TYPE_SHOW){
case 0:
if(i<3){
heardVideoList.add(videoList.get(i));
} else {
contentVideoList1.add(videoList.get(i));
}
break;
case 1:
if(i<1){
heardVideoList.add(videoList.get(i));
} else {
contentVideoList1.add(videoList.get(i));
}
break;
}
}
}
}
//内容是显示类型2(含有下级菜单)
if(TYPE_SHOW==-1){
boolean haveThree=false;
if(videoList.size()<=0){
List<NavModel> modelList=new ArrayList<NavModel>();
List<NavModel> modelList_2=new Select().from(NavModel.class).where(VideoDBConstant.VALID + " = 1 and parent_id = ?",navModel.getNavId()).orderBy(VideoDBConstant.ORDER_ID + " ASC").execute();
modelList.addAll(modelList_2);
for (int j=0;j<modelList_2.size();j++){
List<NavModel> modelList_3=new Select().from(NavModel.class).where(VideoDBConstant.VALID + " = 1 and parent_id = ?",modelList_2.get(j).getNavId()).orderBy(VideoDBConstant.ORDER_ID + " ASC").execute();
modelList.addAll(modelList_3);
if(modelList_3.size()>0){
haveThree=true;
}
}
String str="";
if(haveThree){
str="( valid= 1 and t_a_order != 0 and cId = "+modelList.get(0).getNavId()+" )" ;
for (int k=1;k<modelList.size();k++){
str=str+" or ( valid= 1 and t_a_order != 0 and cId = "+modelList.get(k).getNavId()+" )";
}
videoList =new Select().from(VideoModel.class).where(str).orderBy("t_a_order ASC").execute();
if(videoList.size()<3){
str="( valid= 1 and t_a_order = 0 and cId = "+modelList.get(0).getNavId()+" )" ;
for (int k=1;k<modelList.size();k++){
str=str+" or ( valid= 1 and t_a_order = 0 and cId = "+modelList.get(k).getNavId()+" )";
}
List<VideoModel> videoModelList =new Select().from(VideoModel.class).where(str).orderBy("t_a_order ASC").execute();
for (int i=0;i<videoModelList.size();i++){
videoList.add(videoModelList.get(i));
if(videoList.size()>=3){
break;
}
}
}
}else {
str="( valid= 1 and a_order != 0 and cId = "+modelList.get(0).getNavId()+" )" ;
for (int k=1;k<modelList.size();k++){
str=str+" or ( valid= 1 and a_order != 0 and cId = "+modelList.get(k).getNavId()+" )";
}
videoList =new Select().from(VideoModel.class).where(str).orderBy("a_order ASC").execute();
if(videoList.size()<3){
str="( valid= 1 and a_order = 0 and cId = "+modelList.get(0).getNavId()+" )" ;
for (int k=1;k<modelList.size();k++){
str=str+" or ( valid= 1 and a_order = 0 and cId = "+modelList.get(k).getNavId()+" )";
}
List<VideoModel> videoModelList =new Select().from(VideoModel.class).where(str).orderBy("a_order ASC").execute();
for (int i=0;i<videoModelList.size();i++){
videoList.add(videoModelList.get(i));
if(videoList.size()>=3){
break;
}
}
}
}
}
heardVideoList=new ArrayList<VideoModel>();
for (int i=0;i<videoList.size()&&i<3;i++)
{
heardVideoList.add(videoList.get(i));
}
if(navModel!=null){
contentVideoList2=VideoDBUtil.getHomeContentVideo(navModel,1);
}
}
}
@Override
protected View initViews(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
final View view = inflater.inflate(R.layout.fragment_home_content_item, container, false);
refreshLayout= (PtrClassicFrameLayout) view.findViewById(R.id.refresh_layout);
recyclerView= (RecyclerView) view.findViewById(R.id.recyclerView);
empty= (ImageView) view.findViewById(R.id.emptydate);
refreshLayout.setLastUpdateTimeRelateObject(this);
refreshLayout.setPtrHandler(new PtrHandler() {
@Override
public boolean checkCanDoRefresh(PtrFrameLayout frame, View content, View header) {
return PtrDefaultHandler.checkContentCanBePulledDown(frame, content, header);
}
@Override
public void onRefreshBegin(PtrFrameLayout frame) {
new Thread(new Runnable() {
@Override
public void run() {
refreshData();
}
}).start();
}
});
if(TYPE_SHOW==-1){
recyclerView.setLayoutManager(new LinearLayoutManager(getApplicationContext()));
recyclerView.addItemDecoration(new RecyclerView.ItemDecoration() {
@Override
public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) {
outRect.left = getResources().getDimensionPixelSize(R.dimen.recyclerview_item_10);
outRect.right = getResources().getDimensionPixelSize(R.dimen.recyclerview_item_10);
if(parent.getChildLayoutPosition(view)==0){
outRect.top = getResources().getDimensionPixelSize(R.dimen.recyclerview_item_5);
}
}
});
} else {
GridLayoutManager gridLayoutManager=new GridLayoutManager(context,2,LinearLayoutManager.VERTICAL, false);
gridLayoutManager.setSpanSizeLookup(new GridLayoutManager.SpanSizeLookup() {
@Override
public int getSpanSize(int position) {
if(position==0){
return 2;
}
return 1;
}
});
recyclerView.setLayoutManager(gridLayoutManager);
recyclerView.addItemDecoration(new RecyclerView.ItemDecoration() {
@Override
public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) {
outRect.left = getResources().getDimensionPixelSize(R.dimen.recyclerview_item_5);
outRect.right = getResources().getDimensionPixelSize(R.dimen.recyclerview_item_5);
outRect.bottom = getResources().getDimensionPixelSize(R.dimen.recyclerview_item_5);
outRect.top=getResources().getDimensionPixelSize(R.dimen.recyclerview_item_5);
if(parent.getChildLayoutPosition(view)!=0){
if(parent.getChildLayoutPosition(view)%2==0){//右边小图
outRect.right=getResources().getDimensionPixelSize(R.dimen.recyclerview_item_10);
}else {//左边小图
outRect.left=getResources().getDimensionPixelSize(R.dimen.recyclerview_item_10);
}
}else {
outRect.left = getResources().getDimensionPixelSize(R.dimen.recyclerview_item_10);
outRect.right = getResources().getDimensionPixelSize(R.dimen.recyclerview_item_10);
}
}
});
}
adapter_recylerview=new ContentItemAdapter_recylerview(null,null,null,getApplicationContext(),imgImageLoader,navId,TYPE_SHOW);
recyclerView.setAdapter(adapter_recylerview);
return view;
}
@Override
protected void initWidgetActions()
{
imgImageLoader = ImageLoader.getInstance();
adapter_recylerview.setOnItemClickListener(new ContentItemAdapter_recylerview.MyItemClickListener() {
@Override
public void onItemClick(VideoModel videoModel) {
onMyItemClick(videoModel);
}
});
MyAsyncTask asyncTask=new MyAsyncTask();
asyncTask.execute();
}
public void showData(){
if(videoList.size()==0){
empty.setVisibility(View.VISIBLE);
}
adapter_recylerview.setVideoList(contentVideoList1, contentVideoList2, heardVideoList);
}
@Override
protected void lazyLoad() {
if(navModel==null){
return;
}
if(SettingDBUtil.getInstance(getApplicationContext()).isHomeFirstOpen()&&navModel.getTitle().equals("健康")){
BusProvider.getInstance().post(new ShowHelp());
SettingDBUtil.getInstance(getApplicationContext()).setHomeFirstOpen(false);
}
}
private void onMyItemClick(VideoModel videoModel)
{
if (videoModel.getType() == CommonConstant.TOPIC_TYPE)
{
Intent intent = new Intent(getActivity(), MyListActivity.class);
intent.putExtra(MyListActivity.TYPE, MyListActivity.ActivtyType.TOPIC);
intent.putExtra(TopicFragment.TOPIC_ID, videoModel.getVideoId());
intent.putExtra(MyListActivity.TITLE, videoModel.getTitle());
startActivity(intent);
} else if (videoModel.getType() == CommonConstant.VIDEO_ON_LIVE_TYPE)
{
try
{
if (NetWorkHelper.isNetworkAvailable(getActivity()))
{
if (NetWorkHelper.isWifiDataEnable(getActivity()))
{
Intent intent = new Intent(getActivity(), VideoOnLive.class);
intent.putExtra(VideoDetailActivity.VIDEO_ID, videoModel.getVideoId() + "");
intent.putExtra(VideoDetailActivity.WEB_URL, videoModel.getWebUrl());
startActivity(intent);
getActivity().overridePendingTransition(R.anim.push_left_in, R.anim.no_anim);
} else
{
Hook(videoModel.getVideoId() + "", videoModel.getWebUrl());
}
} else
{
Toast.makeText(getApplicationContext(), "没有网络,无法观看视频。", Toast.LENGTH_LONG).show();
}
} catch (Exception e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
} else
{
Intent intent = new Intent(getActivity(), VideoDetailActivity.class);
intent.putExtra(VideoDetailActivity.VIDEO_ID, videoModel.getVideoId());
startActivity(intent);
getActivity().overridePendingTransition(R.anim.push_left_in, R.anim.no_anim);
}
}
private void Hook(final String videoId, final String webUrl)
{
Builder builder = new Builder(getActivity());
builder.setMessage("温馨提示:非Wi-fi环境下,播放视频会消耗较多流量!");
builder.setPositiveButton("继续播放",
new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface dialog, int whichButton)
{
dialog.dismiss();
Intent intent = new Intent(getActivity(), VideoOnLive.class);
intent.putExtra(VideoDetailActivity.VIDEO_ID, videoId);
intent.putExtra(VideoDetailActivity.WEB_URL, webUrl);
startActivity(intent);
getActivity().overridePendingTransition(R.anim.push_left_in, R.anim.no_anim);
}
});
builder.setNegativeButton("暂不播放",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
dialog.dismiss();
}
});
builder.show();
}
private void refreshData() {
Long lastLoadDataTime = SettingDBUtil.getInstance(context).getLastRefreshDataTime();
final long currentTime=System.currentTimeMillis();
RequestParams params = new RequestParams(VideoConstant.NEW_DATA_REFRESH +lastLoadDataTime);
x.http().get(params, new Callback.CommonCallback<String>() {
@Override
public void onSuccess(final String result) {
Toast.makeText(getApplicationContext(),"更新成功",Toast.LENGTH_SHORT).show();
if (result != null && result.trim().length() > 10) {
new Thread(new Runnable() {
@Override
public void run() {
saveData(result);
}
}).start();
SettingDBUtil.getInstance(context).setRefreshDataTime(currentTime);
}
}
@Override
public void onError(Throwable ex, boolean isOnCallback) {
Toast.makeText(getApplicationContext(),"更新失败",Toast.LENGTH_SHORT).show();
}
@Override
public void onCancelled(CancelledException cex) {
}
@Override
public void onFinished() {
refreshLayout.refreshComplete();
}
});
}
private void saveData(String result) {
JSONObject obj = null;
JSONArray videoArr = null;
try {
obj = new JSONObject(result);
videoArr = obj.optJSONArray(VideoConstant.VIDEOLIST);
} catch (JSONException e) {
}
if (videoArr != null) {
ActiveAndroid.beginTransaction();
try {
for (int i = 0, videoLen = videoArr.length(); i < videoLen; i++) {
VideoModel videoModel = new VideoModel();
JSONObject navObj = videoArr.optJSONObject(i);
videoModel.setVideoId(navObj.optLong(VideoConstant.ID));
videoModel.setType(navObj.optInt(VideoConstant.TYPE));
videoModel.setClicked(false);
videoModel.setTitleUpload(navObj.optString(VideoConstant.TITLE_UPLOAD));
videoModel.setrOrder(navObj.optInt(VideoConstant.RORDER));
videoModel.setrId(navObj.optInt(VideoConstant.RID));
videoModel.setcId(navObj.optInt(VideoConstant.CID));
videoModel.setcOrder(navObj.optInt(VideoConstant.CORDER));
videoModel.settId(navObj.optInt(VideoConstant.TID));
videoModel.settOrder(navObj.optInt(VideoConstant.TORDER));
videoModel.setTitle(navObj.optString(VideoConstant.TITLE));
videoModel.setValid(navObj.optInt(VideoConstant.VALID));
videoModel.setDetail(navObj.optString(VideoConstant.DETAIL));
videoModel.setWebUrl(navObj.optString(VideoConstant.WEBURL));
videoModel.setExpireDate(navObj.optInt(VideoConstant.EXPIREDATE));
videoModel.setShootDate(navObj.optLong(VideoConstant.SHOOTDATE));
videoModel.setIsVip(navObj.optInt(VideoConstant.IS_VIP));
videoModel.setRole(navObj.optString(VideoConstant.ROLE));
videoModel.setPermission(navObj.optInt(VideoDBConstant.PERMISSION));
videoModel.setTags(navObj.optString(VideoConstant.TAGS));
videoModel.setPicDate(navObj.optLong(VideoConstant.PICDATE));
videoModel.setSign(navObj.optInt(VideoConstant.SIGN));
videoModel.setaOrder(navObj.optInt(VideoDBConstant.A_ORDER));
videoModel.settAOrder(navObj.optInt(VideoDBConstant.T_A_ORDER));
try {
VideoDBUtil.deleteVideo(videoModel.getVideoId());
} catch (Exception e) {
e.printStackTrace();
}
if (videoModel.getRole() == null || videoModel.getRole().trim().length() == 0) {
videoModel.setRole(VideoConstant.NULL);
}
videoModel.save();
}
ActiveAndroid.setTransactionSuccessful();
}catch(Exception e) {
}finally {
ActiveAndroid.endTransaction();
}
getActivity().runOnUiThread(new Runnable() {
@Override
public void run() {
BusProvider.getInstance().post(new RefreshEvent(navModel.getParent_id()));//通知更新数据
}
});
}
}
@Subscribe
public void scrollTop(ContentScrollTopEvent contentScrollTopEvent){
if(recyclerView!=null){
recyclerView.smoothScrollToPosition(0);
}
}
@Override
public void onDestroy() {
super.onDestroy();
if(adapter_recylerview!=null){
adapter_recylerview.cancelTimer();
}
}
@Override
public void onResume() {
super.onResume();
BusProvider.getInstance().register(this);
}
@Override
public void onPause() {
super.onPause();
try {
BusProvider.getInstance().unregister(this);//注销
}catch (Exception e){}
}
class MyAsyncTask extends AsyncTask {
@Override
protected Object doInBackground(Object[] params) {
initVideoList();
return null;
}
@Override
protected void onPostExecute(Object o) {
showData();
super.onPostExecute(o);
}
}
}
这是适配器代码:
public class ContentItemAdapter_recylerview extends RecyclerView.Adapter {
public final static int AUDIO_ID = 999999998; //点击“听见安利”的id
public final static int SUBJECT_ID = 7; //点击“主题专区”的id
private List<VideoModel> contentVideoModelList1, contentVideoList, heardVideoList;
private List<HomeContentVideoInfo> contentVideoModelList2;
private Context context;
protected DisplayImageOptions mOptions;
protected ImageLoader mImageLoader;
private int TYPE_SHOW = 0;//0默认头部轮播页面,1为单张大图页面,-1为含有二三级页面
private static final int TYPE_CONTENT = 0;
private static final int TYPE_HEADER = 1;
private int listSize;
public ContentItemAdapter_recylerview(List<VideoModel> contentVideoModelList1, List<HomeContentVideoInfo> contentVideoModelList2, List<VideoModel> heardVideoList, Context context, ImageLoader mImageLoader, long navId, int TYPE_SHOW) {
this.contentVideoModelList1 = contentVideoModelList1;
this.contentVideoModelList2 = contentVideoModelList2;
this.heardVideoList = heardVideoList;
this.context = context;
this.mImageLoader = mImageLoader;
this.navId = navId;
this.TYPE_SHOW = TYPE_SHOW;
mOptions = new DisplayImageOptions.Builder().showImageForEmptyUri(R.drawable.default_pic).showImageOnLoading(R.drawable.default_pic)
.resetViewBeforeLoading(true).cacheInMemory(false).cacheOnDisc(true).imageScaleType(ImageScaleType.EXACTLY)
.bitmapConfig(Bitmap.Config.RGB_565).displayer(new SimpleBitmapDisplayer()).build();
}
//搜索关键字
private String keyword;
protected long navId;
private MyItemClickListener mItemClickListener;
@Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
if (viewType == TYPE_CONTENT) {
if (TYPE_SHOW == 0 || TYPE_SHOW == 1) {
return new ContentViewHolder1(View.inflate(context, R.layout.view_content_item, null));
} else if (TYPE_SHOW == -1) {
return new ContentViewHolder2(View.inflate(context, R.layout.view_home_content_item, null));
}
} else if (viewType == TYPE_HEADER) {
if (TYPE_SHOW == 0 || TYPE_SHOW == -1) {
return new HeaderViewHolderWithViewPager(View.inflate(context, R.layout.home_content_item_header, null));
} else if (TYPE_SHOW == 1) {
return new HeaderViewHolderWithImager(View.inflate(context, R.layout.view_content_home_header, null));
}
}
return null;
}
@Override
public int getItemViewType(int position) {
if (position == 0 && (heardVideoList == null ? false : heardVideoList.size() > 0 ? true : false)) {
return TYPE_HEADER;
}
return TYPE_CONTENT;
}
public void setOnItemClickListener(MyItemClickListener listener) {
this.mItemClickListener = listener;
}
@Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
//头部显示--单张大图
if (holder instanceof HeaderViewHolderWithImager) {
showHeaderViewWithImager((HeaderViewHolderWithImager) holder, heardVideoList.get(0));
}
//头部显示--轮播
if (holder instanceof HeaderViewHolderWithViewPager) {
showHeaderViewWithViewPager((HeaderViewHolderWithViewPager) holder);
}
//头部以下内容显示--类型1
if (holder instanceof ContentViewHolder1) {
VideoModel videoModel = contentVideoModelList1.get(heardVideoList == null ? position : heardVideoList.size() > 0 ? position - 1 : position);
showContentView1((ContentViewHolder1) holder, videoModel);
if (!MyImageLoader.isMemoryCache(context, StorageHelper.getListSmallImgUrl(videoModel), ((ContentViewHolder1) holder).img, mImageLoader)) {
mImageLoader.displayImage(StorageHelper.getListSmallImgUrl(videoModel), ((ContentViewHolder1) holder).img, mOptions);
}
}
//头部以下内容显示--类型2
if (holder instanceof ContentViewHolder2) {
showContentView2((ContentViewHolder2) holder, heardVideoList == null ? position : heardVideoList.size() > 0 ? position - 1 : position);
}
}
public void setVideoList(List<VideoModel> contentVideoModelList1, List<HomeContentVideoInfo> contentVideoModelList2, List<VideoModel> heardVideoList) {
this.contentVideoModelList1 = contentVideoModelList1;
this.contentVideoModelList2 = contentVideoModelList2;
this.heardVideoList = heardVideoList;
notifyDataSetChanged();
}
@Override
public int getItemCount() {
listSize = 0;
switch (TYPE_SHOW) {
case 0:
listSize = heardVideoList == null ? 0 : heardVideoList.size() > 0 ? 1 : 0;
listSize = contentVideoModelList1 == null ? listSize : listSize + contentVideoModelList1.size();
break;
case 1:
listSize = heardVideoList == null ? 0 : 1;
listSize = contentVideoModelList1 == null ? listSize : listSize + contentVideoModelList1.size();
break;
case -1:
listSize = heardVideoList == null ? 0 : heardVideoList.size() > 0 ? 1 : 0;
listSize = contentVideoModelList2 == null ? listSize : listSize + contentVideoModelList2.size();
break;
}
return listSize;
}
/**
* @function 头部--单张大图——SHOW_DATA
* @author mootor
* created at 2016/8/16 17:32
*/
private HomeContentItemAdsAdapter homeContentItemAdsAdapter;
private Timer timer;
private TimerTask task;
private int currentItemPosition = 0;
private void showHeaderViewWithImager(HeaderViewHolderWithImager holder, VideoModel model) {
holder.text.setText(model.getTitle());
holder.audioImg.setVisibility(View.GONE);
if (model.getType() == CommonConstant.TOPIC_TYPE) {
holder.topicImg.setVisibility(View.VISIBLE);
} else {
holder.topicImg.setVisibility(View.GONE);
if (model.getIsVip() == 1 /*&& !UserDBUtil.getInstance(context).isNeedLogin()*/) {// vip
holder.topicImg.setImageResource(R.drawable.corner_vip);
holder.topicImg.setVisibility(View.VISIBLE);
}
if (StorageHelper.isAudioRes(model)) {
holder.audioImg.setVisibility(View.VISIBLE);
}
}
if (model.isClicked()) {
holder.newVideoImg.setVisibility(View.GONE);
} else {
holder.newVideoImg.setVisibility(View.VISIBLE);
}
if (!MyImageLoader.isMemoryCache(context, StorageHelper.getListBigImgUrl(model), holder.img, mImageLoader)) {
mImageLoader.displayImage(StorageHelper.getListBigImgUrl(model), holder.img, mOptions);
}
}
/**
* @function 头部--轮播——SHOW_DATA
* @author mootor
* created at 2016/8/16 18:25
*/
private void showHeaderViewWithViewPager(final HeaderViewHolderWithViewPager holder) {
if (homeContentItemAdsAdapter == null) {
homeContentItemAdsAdapter = new HomeContentItemAdsAdapter(context, heardVideoList, mImageLoader);
holder.viewPager.removeAllViews();
holder.viewPager.setAdapter(homeContentItemAdsAdapter);
initDots(holder);//初始化指示器
homeContentItemAdsAdapter.setOnItemClickListener(new MyItemClickListener() {
@Override
public void onItemClick(VideoModel videoModel) {
if (mItemClickListener != null) {
mItemClickListener.onItemClick(videoModel);
}
}
});
holder.viewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
@Override
public void onPageSelected(int position) {
currentItemPosition = position;
if (heardVideoList.size() < 1) {
return;
}
updateIntroAndDot(holder);
}
@Override
public void onPageScrolled(int position, float positionOffset,
int positionOffsetPixels) {
}
@Override
public void onPageScrollStateChanged(int state) {
}
});
if (heardVideoList.size() > 1) {
holder.topAdTextView.setText(heardVideoList.get(0).getTitle());
//计时轮播
if (timer == null) {
timer = new Timer();
}
if (task == null) {
task = new TimerTask() {
public void run() {
if (holder.viewPager != null)
holder.viewPager.post(new Runnable() {
@Override
public void run() {
holder.viewPager.setCurrentItem(currentItemPosition + 1);
}
});
}
};
timer.schedule(task, 2000, 2000);
}
}
}
}
public void cancelTimer(){
if(timer!=null){
timer.cancel();
}
}
/**
* @function 头部以下内容——类型1——SHOW_DATA
* @author mootor
* created at 2016/8/16 18:25
*/
protected void showContentView1(ContentViewHolder1 holder, VideoModel model) {
SpannableStringBuilder textString = null;
keyword = Valuepass.newInstance().getKeywordsearch();
if (keyword != null) {
textString = TextUtilTools.highlight(model.getTitle(), keyword);
} else {
textString = new SpannableStringBuilder(model.getTitle());
}
holder.text.setText(textString);
holder.audioImg.setVisibility(View.GONE);
holder.topicImg.setVisibility(View.GONE);
if (navId != AUDIO_ID && navId != SUBJECT_ID) {
if (model.getIsVip() == 1 /*&& !UserDBUtil.getInstance(context).isNeedLogin()*/) {// vip
holder.topicImg.setImageResource(R.drawable.corner_vip);
holder.topicImg.setVisibility(View.VISIBLE);
} else if (StorageHelper.isAudioRes(model)) {// 音频
holder.audioImg.setVisibility(View.VISIBLE);
} else if (model.getType() == CommonConstant.TOPIC_TYPE) {// topic
holder.topicImg.setImageResource(R.drawable.home_topic);
holder.topicImg.setVisibility(View.VISIBLE);
}
}
if (model.isClicked()) {
holder.newVideoImg.setVisibility(View.GONE);
} else {
holder.newVideoImg.setVisibility(View.VISIBLE);
}
}
/**
* @function 头部以下内容——类型2——SHOW_DATA
* @author mootor
* created at 2016/8/17 11:51
*/
private void showContentView2(final ContentViewHolder2 holder, final int position) {
if (contentVideoModelList2.get(position).getVideoModelList().size() >= 1) {
holder.content_layout.setVisibility(View.VISIBLE);
holder.contentLayout1.setVisibility(View.VISIBLE);
updateHolder(holder, contentVideoModelList2.get(position).getVideoModelList().get(0), 1, contentVideoModelList2.get(position).getNavModel().getNavId());
final ContentViewHolder2 finalHolder1 = holder;
if (!MyImageLoader.isMemoryCache(context, StorageHelper.getListSmallImgUrl(contentVideoModelList2.get(position).getVideoModelList().get(0)), finalHolder1.img1, mImageLoader)) {
mImageLoader.displayImage(StorageHelper.getListSmallImgUrl(contentVideoModelList2.get(position).getVideoModelList().get(0)), finalHolder1.img1, mOptions);
}
holder.contentLayout1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (mItemClickListener != null) {
VideoModel videoModel = contentVideoModelList2.get(position).getVideoModelList().get(0);
if (!videoModel.isClicked()) {
holder.newVideoImg1.setVisibility(View.GONE);
videoModel.setClicked(true);
videoModel.save();
}
mItemClickListener.onItemClick(videoModel);
}
}
});
} else {
holder.content_layout.setVisibility(View.GONE);
holder.contentLayout1.setVisibility(View.GONE);
holder.contentLayout2.setVisibility(View.GONE);
}
if (contentVideoModelList2.get(position).getVideoModelList().size() >= 2) {
holder.contentLayout2.setVisibility(View.VISIBLE);
updateHolder(holder, contentVideoModelList2.get(position).getVideoModelList().get(1), 2, contentVideoModelList2.get(position).getNavModel().getNavId());
final ContentViewHolder2 finalHolder = holder;
if (!MyImageLoader.isMemoryCache(context, StorageHelper.getListSmallImgUrl(contentVideoModelList2.get(position).getVideoModelList().get(1)), finalHolder.img2, mImageLoader)) {
mImageLoader.displayImage(StorageHelper.getListSmallImgUrl(contentVideoModelList2.get(position).getVideoModelList().get(1)), finalHolder.img2, mOptions);
}
holder.contentLayout2.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (mItemClickListener != null) {
VideoModel videoModel = contentVideoModelList2.get(position).getVideoModelList().get(1);
if (!videoModel.isClicked()) {
holder.newVideoImg2.setVisibility(View.GONE);
videoModel.setClicked(true);
videoModel.save();
}
mItemClickListener.onItemClick(videoModel);
}
}
});
} else {
holder.contentLayout2.setVisibility(View.INVISIBLE);
}
holder.title.setText(contentVideoModelList2.get(position).getNavModel().getTitle());
holder.moreBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
BusProvider.getInstance().post(new ContentItemEven(null, contentVideoModelList2.get(position).getNavModel(), 2, position));
}
});
}
/**
* @function 头部以下内容——类型2——SHOW_DATA
* @author mootor
* created at 2016/8/17 11:52
*/
protected void updateHolder(ContentViewHolder2 holder, VideoModel model, int item, long navId) {
SpannableStringBuilder textString = null;
keyword = Valuepass.newInstance().getKeywordsearch();
if (keyword != null) {
textString = TextUtilTools.highlight(model.getTitle(), keyword);
} else {
textString = new SpannableStringBuilder(model.getTitle());
}
if (item == 1) {
holder.text1.setText(textString);
holder.audioImg1.setVisibility(View.GONE);
holder.topicImg1.setVisibility(View.GONE);
} else {
holder.text2.setText(textString);
holder.audioImg2.setVisibility(View.GONE);
holder.topicImg2.setVisibility(View.GONE);
}
if (navId != AUDIO_ID && navId != SUBJECT_ID) {
if (model.getIsVip() == 1 /*&& !UserDBUtil.getInstance(context).isNeedLogin()*/) {// vip
if (item == 1) {
holder.topicImg1.setImageResource(R.drawable.corner_vip);
holder.topicImg1.setVisibility(View.VISIBLE);
} else {
holder.topicImg2.setImageResource(R.drawable.corner_vip);
holder.topicImg2.setVisibility(View.VISIBLE);
}
} else if (StorageHelper.isAudioRes(model)) {// 音频
if (item == 1) {
holder.audioImg1.setVisibility(View.VISIBLE);
} else {
holder.audioImg2.setVisibility(View.VISIBLE);
}
} else if (model.getType() == CommonConstant.TOPIC_TYPE) {// topic
if (item == 1) {
holder.topicImg1.setImageResource(R.drawable.home_topic);
holder.topicImg1.setVisibility(View.VISIBLE);
} else {
holder.topicImg2.setImageResource(R.drawable.home_topic);
holder.topicImg2.setVisibility(View.VISIBLE);
}
}
}
if (model.isClicked()) {
if (item == 1) {
holder.newVideoImg1.setVisibility(View.GONE);
} else {
holder.newVideoImg2.setVisibility(View.GONE);
}
} else {
if (item == 1) {
holder.newVideoImg1.setVisibility(View.VISIBLE);
} else {
holder.newVideoImg2.setVisibility(View.VISIBLE);
}
}
}
/**
* @author mootor
* created at 2016/8/17 11:40
* @function 头部以下内容——类型2——VIEW
*/
public class ContentViewHolder2 extends RecyclerView.ViewHolder {
private LinearLayout content_layout;
private RelativeLayout contentLayout1;
private RelativeLayout contentLayout2;
private TextView title;
private ImageView moreBtn;
private ImageView img1;
private TextView text1;
private ImageView audioImg1;
private ImageView newVideoImg1;
private ImageView topicImg1;
private ImageView img2;
private TextView text2;
private ImageView audioImg2;
private ImageView newVideoImg2;
private ImageView topicImg2;
public ContentViewHolder2(View itemView) {
super(itemView);
content_layout = (LinearLayout) itemView.findViewById(R.id.content_layout);
contentLayout1 = (RelativeLayout) itemView.findViewById(R.id.content_layout1);
contentLayout2 = (RelativeLayout) itemView.findViewById(R.id.content_layout2);
title = (TextView) itemView.findViewById(R.id.titleTv);
moreBtn = (ImageView) itemView.findViewById(R.id.moreBtn);
img1 = (ImageView) itemView.findViewById(R.id.content_img1);
text1 = (TextView) itemView.findViewById(R.id.content_text1);
audioImg1 = (ImageView) itemView.findViewById(R.id.audio_mark_img1);
newVideoImg1 = (ImageView) itemView.findViewById(R.id.new_video_img1);
topicImg1 = (ImageView) itemView.findViewById(R.id.topic_img1);
img2 = (ImageView) itemView.findViewById(R.id.content_img2);
text2 = (TextView) itemView.findViewById(R.id.content_text2);
audioImg2 = (ImageView) itemView.findViewById(R.id.audio_mark_img2);
newVideoImg2 = (ImageView) itemView.findViewById(R.id.new_video_img2);
topicImg2 = (ImageView) itemView.findViewById(R.id.topic_img2);
}
}
/**
* @author mootor
* created at 2016/8/17 11:55
* @function 头部——单张大图——VIEW
*/
private class HeaderViewHolderWithImager extends RecyclerView.ViewHolder {
RelativeLayout headerLayout;
ImageView img;
TextView text;
ImageView audioImg;
ImageView newVideoImg;
ImageView topicImg;
public HeaderViewHolderWithImager(View itemView) {
super(itemView);
headerLayout = (RelativeLayout) itemView.findViewById(R.id.header_box);
img = (ImageView) itemView.findViewById(R.id.content_img);
text = (TextView) itemView.findViewById(R.id.content_text);
audioImg = (ImageView) itemView.findViewById(R.id.audio_mark_img);
newVideoImg = (ImageView) itemView.findViewById(R.id.new_video_img);
topicImg = (ImageView) itemView.findViewById(R.id.topic_img);
headerLayout.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (mItemClickListener != null) {
newVideoImg.setVisibility(View.GONE);
VideoModel videoModel = heardVideoList.get(0);
mItemClickListener.onItemClick(videoModel);
}
}
});
}
}
/**
* @author mootor
* created at 2016/8/17 11:56
* @function 头部轮播——VIEW
*/
public class HeaderViewHolderWithViewPager extends RecyclerView.ViewHolder {
private ViewPager viewPager;
private TextView topAdTextView;
private LinearLayout topAdDotLayout;
private ImageView topToLeftBtn, topToRightBtn;
public HeaderViewHolderWithViewPager(View itemView) {
super(itemView);
viewPager = (ViewPager) itemView.findViewById(R.id.viewPager);
topAdTextView = (TextView) itemView.findViewById(R.id.tv_intro);
topAdDotLayout = (LinearLayout) itemView.findViewById(R.id.dot_layout);
topToLeftBtn = (ImageView) itemView.findViewById(R.id.topic_left_img);
topToRightBtn = (ImageView) itemView.findViewById(R.id.topic_right_img);
topToLeftBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (viewPager != null && heardVideoList.size() > 1) {
viewPager.setCurrentItem(currentItemPosition - 1);
}
}
});
topToRightBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (viewPager != null && heardVideoList.size() > 1) {
viewPager.setCurrentItem(currentItemPosition + 1);
}
}
});
try {//这里设置轮播切换过程的缓冲时间500毫秒
Field field = ViewPager.class.getDeclaredField("mScroller");
field.setAccessible(true);
ViewPagerScroller scroller = new ViewPagerScroller(context,
new AccelerateInterpolator());
field.set(viewPager, scroller);
scroller.setmDuration(500);
} catch (Exception e) {
}
}
}
/**
* @author mootor
* created at 2016/8/17 11:56
* @function 头部以下内容——类型1——VIEW
*/
protected class ContentViewHolder1 extends RecyclerView.ViewHolder {
public ImageView img, audioImg, newVideoImg, topicImg;
public TextView text;
public RelativeLayout layout;
public ContentViewHolder1(View itemView) {
super(itemView);
layout = (RelativeLayout) itemView.findViewById(R.id.layout);
img = (ImageView) itemView.findViewById(R.id.content_img);
text = (TextView) itemView.findViewById(R.id.content_text);
audioImg = (ImageView) itemView.findViewById(R.id.audio_mark_img);
newVideoImg = (ImageView) itemView.findViewById(R.id.new_video_img);
topicImg = (ImageView) itemView.findViewById(R.id.topic_img);
layout.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (mItemClickListener != null) {
newVideoImg.setVisibility(View.GONE);
VideoModel videoModel = contentVideoModelList1.get(heardVideoList == null ? getPosition() : heardVideoList.size() > 0 ? getPosition() - 1 : getPosition());
mItemClickListener.onItemClick(videoModel);
videoModel.setClicked(true);
videoModel.save();
}
}
});
}
}
/**
* @author mootor
* created at 2016/8/17 11:54
* @function item点击监听
*/
public interface MyItemClickListener {
void onItemClick(VideoModel videoModel);
}
/**
* 初始化dot——头部轮播
*/
private void initDots(HeaderViewHolderWithViewPager viewHolder) {
for (int i = 0; i < heardVideoList.size(); i++) {
View view = new View(context);
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(15, 15);
if (i != 0) {
params.leftMargin = 8;
}
view.setLayoutParams(params);
view.setBackgroundResource(R.drawable.selector_dot);
if (i != 0) {
view.setEnabled(false);
}
viewHolder.topAdDotLayout.addView(view);
}
}
/**
* 更新文本——头部轮播
*/
private void updateIntroAndDot(HeaderViewHolderWithViewPager view) {
try {
int currentPage = view.viewPager.getCurrentItem() % heardVideoList.size();
view.topAdTextView.setText(heardVideoList.get(currentPage).getTitle());
for (int i = 0; i < view.topAdDotLayout.getChildCount(); i++) {
view.topAdDotLayout.getChildAt(i).setEnabled(i == currentPage);
}
} catch (Exception e) {
}
}
}
안녕하세요, 저는 이것보다 조금 더 복잡한 효과를 냈는데 이것도 헤드 캐러셀 + 목록이 있는 ViewPager+Fragment의 조합이지만 ViewPager+Fragment의 조합 효과에 대해서는 동적입니다. 일반적으로 인터넷의 많은 제안은
1. Fragment는 지연 로딩 방식을 채택합니다
2. FragmentStateAdapter를 사용해 봅니다(특정한 이유로 Baidu를 사용할 수 있음)
3. 반복적인 네트워크 요청을 피하기 위해 캐싱 메커니즘을 사용합니다. 🎜> 4. 네트워크 요청 지연
5. 뛰어난 오픈 소스 프레임워크를 사용합니다. 예를 들어 그림 프레임워크는 Fresco를 뛰어난 성능으로 사용할 수 있습니다.
6. UI 스레드에서 너무 많은 시간이 소요되는 작업을 방지하려는 노력과 같은 몇 가지 기본 지식입니다.
7. 수명 주기 제어(메모리 누수 방지)와 같은 Fragment에 대한 몇 가지 기본 지식입니다. 또는 null 포인터), 그러면 상태가 저장될 수 있습니다
당시에 이러한 방법을 채택했는데 저사양 컴퓨터에서는 효과가 괜찮았습니다.
레이아웃은 무엇입니까
코드를 살펴보니 캐시되지 않았습니다
최종 해결을 기다리고 있습니다!