我们都知道Fragment是碎片化的View,和Activity相生相息,在安卓开发过程中使用Activity结合多个碎片化View可以更简洁和方便的管理视图生命周期和节省内存开销。
在日常开发中我们大多数情况下都是与后台协议商定了固定的标签数目,以创建相应的Fragment来展示,但是如果我们的顶部标签栏中的标题个数、内容都不确定的话,怎么办?Fragment要怎么创建和匹配?
特别是如果我们有大量的标签,四五十个,我们总不可能去创建四五十个相应的Fragment页面吧,如果是这样我的项目结构一定会大乱而且不堪。
首先我们要根据接口获取标签栏中的所有标签数
//TODO 获取喜马拉雅分类列表
private void getHiLa_ClassData(){
if(albumsListParamter!=null) {
Commander.tagListByCategoryId(albumsListParamter.getCategoryId(), new HttpCmdCallback<List<TagListInCategory>>() {
@Override
public void onResponse(List<TagListInCategory> object, int code) {
if(code==0){
setHeadViewDatas(object);
}
}
});
}
}
当code==0代表我们已经拿到了标签内容然后将所有的标签放到List集合中,并抛出到主线程
//TODO 通过接口获取头部标签数据
private void setHeadViewDatas(List<TagListInCategory> object){
tagListDatas=object;
for(int i=0;i<tagListDatas.size();i++){
mDatas.add(tagListDatas.get(i).getTagName());
}
Message message=new Message();
message.what=0;
message.obj=mDatas;
handler.sendMessage(message);
}
然后在Handler里面创建并设置所有相对应的Fragment和标签
private Handler handler=new Handler(new Handler.Callback() {
@Override
public boolean handleMessage(Message msg) {
switch (msg.what){
case 0:
List<String> datas= (List<String>) msg.obj;
initDatas();
//设置Tab上的标题
mIndicator.setTabItemTitles(datas);
mViewPager.setAdapter(mAdapter);
//设置关联的ViewPager
mIndicator.setViewPager(mViewPager,mScrollView,0);
break;
}
return false;
}
});
//TODO 设置Fragment
private void initDatas()
{
for(int i=0;i<mDatas.size();i++){
albumsListParamter.setTagName(mDatas.get(i));
Himalaya_Radio_ClassFragment fragment = new Himalaya_Radio_ClassFragment().newInstance(mDatas.get(i),albumsListParamter);
mTabContents.add(fragment);
}
mAdapter = new FragmentPagerAdapter(getSupportFragmentManager())
{
@Override
public int getCount()
{
return mTabContents.size();
}
@Override
public Fragment getItem(int position)
{
return mTabContents.get(position);
}
};
}
通过initDatas()这个方法,使用单例来根据标签数量来创建fragment,并将相应标签的参数信息传递到Fragment页面,以便于在显示的时候去请求该页面数据
由于我们的Fragment是支持ViewPager跟随滑动的,所以需要填充FragmentPagerAdapter,Himalaya_Radio_ClassFragment这个Fragment,是我们的母类
进入这个Fragment,首先看下从Activity传递过来的数据,我们具体的接收方法
public Himalaya_Radio_ClassFragment newInstance(String title, Parameters.AlbumsListParamter albumsListParamter)
{
Bundle bundle = new Bundle();
bundle.putString("title",title);
bundle.putSerializable("param",albumsListParamter);
Himalaya_Radio_ClassFragment fragment = new Himalaya_Radio_ClassFragment();
fragment.setArguments(bundle);
return fragment;
}
我们把标签内容和具体的参数信息集合通过创建Himalaya_Radio_ClassFragment传递过去,以便去请求接口数据
然后我们需要用到一个非常关键的方法
public void setUserVisibleHint(boolean isVisibleToUser) {
super.setUserVisibleHint(isVisibleToUser);
if(isVisibleToUser){//TODO fragment 可见的时候
setDatas();
}
}
也就是说,当我们的Fragment可见的时候才去接收需要请求接口的参数信息,否则这些数个Fragment请求的数据会是相同的(经过验证测试)
然后在setDatas()方法里面我们去请求接口数据,来填充对应的Fragment
private void setDatas(){
Bundle arguments = getArguments();
if (arguments != null)
{
mTitle = arguments.getString("title");
albumsListParamter= (Parameters.AlbumsListParamter) arguments.getSerializable("param");
albumsListParamter.setTagName(mTitle);
if(albumsListParamter!=null){
setFragmentData();
}
}
}
在setFragmentData()方法中我们拿到数据就可以填充GridView了
//TODO 切换时间根据不同tagName去请求数据刷新fragment
private void setFragmentData(){
Commander.getHimalayaAlbumsList(albumsListParamter, new HttpCmdCallback<AlbumsListInfo>() {
@Override
public void onResponse(final AlbumsListInfo object, int code) {
if(code==0){
getActivity().runOnUiThread(new Runnable() {
@Override
public void run() {
// listAlbums.clear();
listAlbums.addAll(object.getAlbums());
if(isOnRefresh){
if(object.getAlbums().size()==0){
isOnRefresh = false;
Toast.makeText(getActivity(),"没有更多了",Toast.LENGTH_SHORT).show();
refreshView.loadmoreFinish(PullToRefreshLayout.SUCCEED);
currentPageNum=currentPageNum-1;
}else {
isOnRefresh = false;
Toast.makeText(getActivity(), "加载成功", Toast.LENGTH_SHORT).show();
refreshView.loadmoreFinish(PullToRefreshLayout.SUCCEED);
commonAdapter.notifyDataSetChanged();
}
}else {
loadingLayout.setVisibility(View.INVISIBLE);
setGridView(listAlbums);
if(listAlbums.size()<20){
loadmore_view.setVisibility(View.GONE);
refreshView.setVisibility(View.VISIBLE);
}else {
refreshView.setVisibility(View.VISIBLE);
loadmore_view.setVisibility(View.VISIBLE);
//TODO 只有当数据加载出来的时候才允许上拉加载,否则会导致bug
refreshView.setOnRefreshListener(new PullToRefreshLayout.OnRefreshListener() {
@Override
public void onRefresh(PullToRefreshLayout pullToRefreshLayout) {
}
@Override
public void onLoadMore(PullToRefreshLayout pullToRefreshLayout) {
currentPageNum = currentPageNum + 1;
albumsListParamter.setPage(currentPageNum+"");
isOnRefresh=true;
setFragmentData();
}
});
}
}
}
});
}else{
currentPageNum=currentPageNum-1;
refreshView.loadmoreFinish(PullToRefreshLayout.SUCCEED);
}
}
});
}
private void setGridView(List<AlbumsListInfo.AlbumsInfo> listAlbumInfos){//TODO 填充GridView
commonAdapter=new CommonAdapter<AlbumsListInfo.AlbumsInfo>(getActivity().getApplicationContext(),listAlbumInfos,R.layout.item_himalaya_radio_listview) {
@Override
public void convert(ViewHolder viewHolder, final AlbumsListInfo.AlbumsInfo item, final long position) {
// final Bitmap bmp = BitmapFactory.decodeResource(getResources(),R.drawable.about_us);
DraweeController controller = Fresco.newDraweeControllerBuilder()
.setUri(item.getCoverUrlMiddle())
.setAutoPlayAnimations(true)
.build();
viewHolder.getFresoView(R.id.img).setController(controller);
// viewHolder.setImageBitmap(R.id.img,bmp);
viewHolder.setText(R.id.img_text,item.getAlbumTitle());
viewHolder.getConVertView().setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Bundle bundle=new Bundle();
bundle.putInt("bundle_music_playpage_from",7);
bundle.putString("bundle_music_playpage_pic",SpeakerDeviceFragment.MusicPlayInfo.getCurrentPlayMusicBgUrl());
bundle.putString("bundle_music_playpage_title",item.getAlbumTitle());
bundle.putString("bundle_music_playpage_id",item.getId());
bundle.putString("bundle_music_bg_url",item.getCoverUrlMiddle());
bundle.putString("bundle_music_lyrics",item.getAlbumIntro());
bundle.putSerializable("AlbumsByIdParamter",new Parameters.AlbumsByIdParamter(item.getId(), Parameters.AlbumsByIdParamter.ASC,"1","20"));
Intent intent=new Intent(getActivity(),SpeakerPlayPageActivity.class);
intent.putExtras(bundle);
startActivity(intent);
getActivity().overridePendingTransition(R.anim.move_right_in_activity, R.anim.move_left_out_activity);
}
});
}
};
gridView.setAdapter(commonAdapter);
}
ok,任务完成,欢迎大家到交流群里面分享一些惊天地泣鬼神的代码,或者编程思想,贴下,Android代码艺术:128672634,如果你不仅仅是把安卓当作一份工作,而是包含坚持和热爱!