##基类
public class Utils {
private Handler handler;
private static Utils instance;
private Utils() {
handler = new Handler();
}
public static Utils getInstance(){
if (instance==null){
synchronized (Utils.class){
if (instance==null){
instance = new Utils();
}
}
}
return instance;
}
//Handler
public void getRequest4(final String apiUrl, final Class clazzBean, final NetCallback callback) {
new Thread(new Runnable() {
@Override
public void run() {
final Object object = getRequest2(apiUrl, clazzBean);
if (object != null) {
mHandler.post(new Runnable() {
@Override
public void run() {
callback.onSuccess(object);
}
});
} else {
mHandler.post(new Runnable() {
@Override
public void run() {
callback.onFail("请求失败");
}
});
}
}
}).start();
}
public void getRequest3(final String apiurl, final Class clazz, final UtilsCallback callback){
new AsyncTask<String, Void, Object>() {
@Override
protected Object doInBackground(String... strings) {
return getRequest2(strings[0], clazz);
}
@Override
protected void onPostExecute(Object o) {
if (o==null){
callback.onFail("请求失败");
}else {
callback.onSuccess(o);
}
}
}.execute(apiurl);
//executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, apiUrl);
}
public interface UtilsCallback<T>{
void onSuccess(T o);
void onFail(String msg);
}
/**
* 执行一个网络请求
*
* @param apiUrl
* @param clazzBean
* @param <T>
* @return 返回Bean类
*/
public T getRequest2(String apiurl,Class clazz){
Object o;
String request = getRequest(apiurl);
Gson gson = new Gson();
o = gson.fromJson(request, clazz);
return (T)o;
}
/**
* 执行一个网络请求
*
* @param apiUrl
* @return 返回Strinng结果
*/
public String getRequest(String apiurl){
String steam = “”;
try {
URL url = new URL(apiurl);
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestMethod(“GET”);
urlConnection.setConnectTimeout(5000);
urlConnection.setReadTimeout(5000);
int responseCode = urlConnection.getResponseCode();
if (responseCode==HttpURLConnection.HTTP_OK){
steam = getSteam(urlConnection.getInputStream());
}
} catch (Exception e) {
e.printStackTrace();
}
return steam;
}
private String getSteam(InputStream inputStream) throws Exception {
StringBuilder stringBuilder = new StringBuilder();
InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
for (String tmp = bufferedReader.readLine();tmp != null;tmp = bufferedReader.readLine()){
stringBuilder.append(tmp);
}
return stringBuilder.toString();
}
private Context context;
//判断有没有网
public boolean hasNotwotk(Context context){
this.context=context;
ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetworkInfo = cm.getActiveNetworkInfo();
return activeNetworkInfo!=null&&activeNetworkInfo.isAvailable();//有没有开启网络
}
//是否是手机网
public boolean isMobileNotwork(){
/*ConnectivityManager manager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetworkInfo1 = manager.getActiveNetworkInfo();*/
//网络管理者
ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
//获取当前网络状态
NetworkInfo activeNetworkInfo = cm.getActiveNetworkInfo();
//判断网络类型
return activeNetworkInfo!=null&&activeNetworkInfo.getType()==TYPE_MOBILE;
}
}
##BaseActivity
public abstract class BaseActivity extends AppCompatActivity {
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(getLayoutResId());
initData();
initView();
}
protected abstract int getLayoutResId();
protected abstract void initData();
protected abstract void initView();
}
##BaseFragment
public abstract class BaseFragment extends Fragment {
@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
return inflater.inflate(getLayoutResId(),container,false);
}
@Override
public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
initData();
initView(view);
}
protected abstract int getLayoutResId();
protected abstract void initData();
protected abstract void initView(View view);
}
##App
public class App extends Application {
//Activity Service Receive 前回调
//在contentprovider 后调用
@Override
public void onCreate() {
super.onCreate();
//全局图片如何显示
DisplayImageOptions options = new DisplayImageOptions.Builder()
.cacheInMemory(true)
.cacheOnDisk(true)
.showImageOnLoading(R.mipmap.ic_launcher)
.showImageOnFail(R.mipmap.ic_launcher)
.showImageForEmptyUri(R.mipmap.ic_launcher)
.bitmapConfig(Bitmap.Config.RGB_565)
.build();
ImageLoaderConfiguration configuration = new ImageLoaderConfiguration.Builder(this)
.memoryCacheSizePercentage(20)
//图片缓存路径
.diskCache(new UnlimitedDiskCache(new File(Environment.getExternalStorageDirectory(),"a")))
// .diskCache(new UnlimitedDiskCache(new File(getCacheDir(), "images")))
.defaultDisplayImageOptions(options)
.build();
ImageLoader.getInstance().init(configuration);
}
//应用结束回调 真实设备上不会回调
@Override
public void onTerminate() {
super.onTerminate();
}
//当内存过低的时候调用
@Override
public void onLowMemory() {
//释放内存
super.onLowMemory();
}
}
##tab+viewpager+频道管理
public class FragmentOne extends BaseFragment{
private TabLayout tab;
private ViewPager pager;
private Button bt;
private ArrayList list;
private Tabadapter tabadapter;
@Override
protected int getLayoutResId() {
return R.layout.fragmentone;
}
@Override
protected void initView(View view) {
tab = view.findViewById(R.id.tab);
pager = view.findViewById(R.id.pager);
tabadapter = new Tabadapter(getChildFragmentManager());
pager.setAdapter(tabadapter);
tab.setupWithViewPager(pager);
bt = view.findViewById(R.id.bt);
bt.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//ChannelActivity.startChannelActivity((AppCompatActivity) getActivity(),list);
Gson gson = new Gson();
String s = gson.toJson(list);
Intent intent = new Intent(getActivity(),ChannelActivity.class);
intent.putExtra(RESULT_JSON_KEY,s);
startActivityForResult(intent,REQUEST_CODE);
}
});
}
@Override
protected void initData() {
list = new ArrayList<>();
list.add(new ChannelBean("111",true));
list.add(new ChannelBean("222",true));
list.add(new ChannelBean("333",true));
list.add(new ChannelBean("444",true));
list.add(new ChannelBean("555",true));
list.add(new ChannelBean("666",false));
list.add(new ChannelBean("777",false));
list.add(new ChannelBean("888",false));
list.add(new ChannelBean("999",false));
tabadapter.setList(list);
}
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode==REQUEST_CODE&&resultCode==ChannelActivity.RESULT_CODE){
String stringExtra = data.getStringExtra(RESULT_JSON_KEY);
Gson gson = new Gson();
List<ChannelBean> o = (List<ChannelBean>) gson.fromJson(stringExtra, new TypeToken<List<ChannelBean>>(){}.getType());
tabadapter.setList(o);
}
}
}
##请求数据
public class FragmentFive extends BaseFragment{
private PullToRefreshListView pull;
private Myadapter myadapter;
@Override
protected int getLayoutResId() {
return R.layout.fragmentfive;
}
@Override
protected void initView(View view) {
pull = view.findViewById(R.id.pull);
myadapter = new Myadapter(getActivity());
pull.setAdapter(myadapter);
pull.onRefreshComplete();
pull.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener2<ListView>() {
@Override
public void onPullDownToRefresh(PullToRefreshBase<ListView> refreshView) {
page=1;
initData();
}
@Override
public void onPullUpToRefresh(PullToRefreshBase<ListView> refreshView) {
initData();
}
});
}
private int page=1;
private final int count = 10;
private String relase="http://172.17.8.100/movieApi/movie/v1/findReleaseMovieList?";
private String hot="http://172.17.8.100/movieApi/movie/v1/findHotMovieList?";
@Override
protected void initData() {
Utils.getInstance().getRequest3(hot+"page="+page+"&count="+count,NewHot.class, new Utils.UtilsCallback<NewHot>() {
@Override
public void onSuccess(NewHot o) {
if (page==1){
myadapter.setHot(o.getResult());
}else {
myadapter.addHot(o.getResult());
}
page++;
pull.onRefreshComplete();
}
@Override
public void onFail(String msg) {
pull.onRefreshComplete();
Toast.makeText(getActivity(),"请求Hot错误",Toast.LENGTH_SHORT).show();
}
});
}
}
##tab+频道管理 适配器
public class Tabadapter extends FragmentPagerAdapter {
private List<ChannelBean> list;
/*private String[] s = new String[]{
"111","222","333","444","555"
};*/
public Tabadapter(FragmentManager fm) {
super(fm);
list = new ArrayList<>();
}
public void setList(List<ChannelBean> list) {
if (list!=null) {
this.list = list;
notifyDataSetChanged();
}
}
@Override
public Fragment getItem(int i) {
switch (i){
case 0:
return new FragmentTab1();
default:
return new FragmentTab2();
}
}
@Override
public int getCount() {
return list.size();
}
@Nullable
@Override
public CharSequence getPageTitle(int position) {
if (list.get(position).isSelect()){
return list.get(position).getName();
}
return null;
}
}
/*public class Tabadapter extends FragmentPagerAdapter {
private String[] s = new String[]{
“正在热映”,“即将热映”
};
public Tabadapter(FragmentManager fm) {
super(fm);
}
@Override
public Fragment getItem(int i) {
switch (i){
case 0:
return new FragmentOne();
case 1:
return new FragmentThree();
}
return null;
}
@Override
public int getCount() {
return s.length;
}
@Nullable
@Override
public CharSequence getPageTitle(int position) {
return s[position];
}
}*/
##列表适配器
public class Myadapter extends BaseAdapter {
private Context context;
private List<NewHot.HotBean> hot;
public Myadapter(Context context) {
this.context = context;
this.hot = new ArrayList<>();
}
public void setHot(List<NewHot.HotBean> hot) {
if (hot!=null){
this.hot = hot;
}
notifyDataSetChanged();
}
public void addHot(List<NewHot.HotBean> hot){
if (hot!=null){
this.hot.addAll(hot);
}
notifyDataSetChanged();
}
@Override
public int getCount() {
return hot.size();
}
@Override
public Object getItem(int position) {
return hot.get(position);
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
HotViewHolder hotViewHolder;
if (convertView==null){
convertView = LayoutInflater.from(context).inflate(R.layout.hot_item,parent,false);
hotViewHolder = new HotViewHolder(convertView);
}else {
hotViewHolder = (HotViewHolder) convertView.getTag();
}
hotViewHolder.bindHot((NewHot.HotBean) getItem(position));
return convertView;
}
class HotViewHolder{
TextView hname,hdata;
ImageView hiv_img;
public HotViewHolder(View convertView) {
hname = convertView.findViewById(R.id.hname);
hdata = convertView.findViewById(R.id.hdata);
hiv_img = convertView.findViewById(R.id.hiv_img);
convertView.setTag(this);
}
public void bindHot(NewHot.HotBean item) {
hname.setText(item.getName());
hdata.setText(item.getSummary());
ImageLoader.getInstance().displayImage(item.getImageUrl(),hiv_img);
}
}
}
##viewpager 和 列表 适配器
public class Infoadapter extends BaseAdapter {
private Context context;
private List<BannerBean.Data> banner;
private List<NewsBean.ResultBean> news;
public Infoadapter(Context context) {
this.context = context;
banner = new ArrayList<>();
news = new ArrayList<>();
}
public void setBanner(List<BannerBean.Data> banner) {
if (banner!=null) {
this.banner = banner;
notifyDataSetChanged();
}
}
public void setNews(List<NewsBean.ResultBean> news) {
if (news!=null) {
this.news = news;
}notifyDataSetChanged();
}
public void addNews(List<NewsBean.ResultBean> news){
if (news!=null) {
this.news.addAll(news);
}
notifyDataSetChanged();
}
@Override
public int getViewTypeCount() {
return 2;
}
@Override
public int getItemViewType(int position) {
if (banner.size()>0&&position==0){
return 0;
}
return 1;
}
@Override
public int getCount() {
return banner.size()>0?news.size()+1:news.size();
}
@Override
public NewsBean.ResultBean getItem(int position) {
if (banner.size()>0){
if (position==0){
return null;
}
return news.get(position-1);
}
return news.get(position);
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
if (getItemViewType(position)==0){
bannerViewHolder bannerviewHolder;
if (convertView==null){
convertView = LayoutInflater.from(context).inflate(R.layout.banner_item,parent,false);
bannerviewHolder = new bannerViewHolder(convertView);
}else {
bannerviewHolder = (bannerViewHolder) convertView.getTag();
}
bannerviewHolder.bindBanner(banner);
}else {
newsViewHolder newsviewHolder;
if (convertView == null) {
convertView = LayoutInflater.from(context).inflate(R.layout.list_item, parent, false);
newsviewHolder = new newsViewHolder(convertView);
} else {
newsviewHolder = (newsViewHolder) convertView.getTag();
}
newsviewHolder.bindnews(getItem(position));
}
return convertView;
}
class bannerViewHolder{
private Mybanneradapter mybanneradapter;
ViewPager bannerpager;
private Handler handler = new Handler(){
@Override
public void handleMessage(Message msg) {
int i =0;
if (msg.what==1){
i = bannerpager.getCurrentItem();
i++;
bannerpager.setCurrentItem(i);
handler.sendEmptyMessageDelayed(1,3000);
}
}
};
public bannerViewHolder(View convertView) {
bannerpager = convertView.findViewById(R.id.bannerpager);
mybanneradapter = new Mybanneradapter();
bannerpager.setAdapter(mybanneradapter);
convertView.setTag(this);
}
public void bindBanner(List<BannerBean.Data> item) {
mybanneradapter.setList(item);
handler.removeMessages(1);
if (item.size()>1){
bannerpager.setCurrentItem(item.size()*5000);
handler.sendEmptyMessageDelayed(1,3000);
}
}
}
class newsViewHolder{
TextView name,summary;
ImageView icon;
public newsViewHolder(View convertView) {
name = convertView.findViewById(R.id.name);
summary = convertView.findViewById(R.id.summary);
icon = convertView.findViewById(R.id.icon);
convertView.setTag(this);
}
public void bindnews(NewsBean.ResultBean item) {
name.setText(item.getName());
summary.setText(item.getSummary());
ImageLoader.getInstance().displayImage(item.getImageUrl(),icon);
}
}
}
##请求数据 轮播和列表
public class InfoFragment extends BaseFragment{
private Infoadapter infoadapter;
private PullToRefreshListView pull;
@Override
protected void initView(View view) {
pull = view.findViewById(R.id.pull);
pull.setMode(PullToRefreshListView.Mode.BOTH);
infoadapter = new Infoadapter(getActivity());
pull.setAdapter(infoadapter);
pull.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener2<ListView>() {
@Override
public void onPullDownToRefresh(PullToRefreshBase<ListView> refreshView) {
//刷新
page=1;
initData();
}
@Override
public void onPullUpToRefresh(PullToRefreshBase<ListView> refreshView) {
//加载
requestNews();
}
});
}
private int page =1;
private final int count = 10;
private String bannerUrl = "http://www.zhaoapi.cn/quarter/getAd";
//page=1&count=10
private String newsUrl = "http://172.17.8.100/movieApi/movie/v1/findHotMovieList?";
@Override
protected void initData() {
requestBanner();
requestNews();
}
private void requestNews() {
Utils.getInstance().getRequest3(newsUrl + "page=" + page + "&count=" + count,
NewsBean.class, new Utils.NetCallback<NewsBean>() {
@Override
public void onSuccess(NewsBean o) {
if (page==1){
infoadapter.setNews(o.getResult());
}else {
infoadapter.addNews(o.getResult());
}
page++;
pull.onRefreshComplete();
if (o.getResult().size()<count){
pull.setMode(PullToRefreshBase.Mode.PULL_FROM_START);
}else {
pull.setMode(PullToRefreshBase.Mode.BOTH);
}
}
@Override
public void onFail(String msg) {
pull.onRefreshComplete();
Toast.makeText(getActivity(), "请求News错误", Toast.LENGTH_SHORT).show();
}
});
}
private void requestBanner() {
Utils.getInstance().getRequest3(bannerUrl, BannerBean.class, new Utils.NetCallback<BannerBean>() {
@Override
public void onSuccess(BannerBean o) {
infoadapter.setBanner(o.getData());
}
@Override
public void onFail(String msg) {
Toast.makeText(getActivity(), "请求Banner错误", Toast.LENGTH_SHORT).show();
}
});
}
@Override
protected int getLayoutResId() {
return R.layout.infofragment;
}
}
作者:weixin_44022413
来源:CSDN
原文:https://blog.csdn.net/weixin_44022413/article/details/85040615
版权声明:本文为博主原创文章,转载请附上博文链接!