//添加的权限:
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" /> <uses-permission android:name="android.permission.INTERNET" /> <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" /> <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />//添加的依赖:
compile 'com.android.support:recyclerview-v7:25.3.1' compile 'com.youth.banner:banner:1.4.9' compile 'com.google.code.gson:gson:2.8.1' compile 'com.github.bumptech.glide:glide:4.0.0-RC1' compile 'org.xutils:xutils:3.5.0' compile 'com.nostra13.universalimageloader:universal-image-loader:1.9.5'
用xutils时,创建一个类继承Application ,记得在清单中配置public class BaseApp extends Application { @Override public void onCreate() { super.onCreate(); x.Ext.init(this); x.Ext.setDebug(BuildConfig.DEBUG); } }
1.MainActivity 类
public class MainActivity extends AppCompatActivity implements View.OnClickListener { private RadioButton ra1; private RadioButton ra2; private RadioButton ra3; private RadioButton ra4; private Fragment fragment; private ManhuaFrag manhuaFra; private FaxianFrag faxianFrag; private ShequFrag shequFrag; private MesFrag mesFrag; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); ra1 = (RadioButton) findViewById(R.id.ra1); ra2 = (RadioButton) findViewById(R.id.ra2); ra3 = (RadioButton) findViewById(R.id.ra3); ra4 = (RadioButton) findViewById(R.id.ra4); ra1.setOnClickListener(this); ra2.setOnClickListener(this); ra3.setOnClickListener(this); ra4.setOnClickListener(this); //设置默认的加载页面 addFrafment(new ManhuaFrag()); } @Override public void onClick(View view) { switch (view.getId()) { case R.id.ra1: if (manhuaFra == null) { manhuaFra = new ManhuaFrag(); } addFrafment(manhuaFra); break; case R.id.ra2: if (faxianFrag == null) { faxianFrag = new FaxianFrag(); } addFrafment(faxianFrag); break; case R.id.ra3: if (shequFrag == null) { shequFrag = new ShequFrag(); } addFrafment(shequFrag); break; case R.id.ra4: if (mesFrag == null) { mesFrag = new MesFrag(); } addFrafment(mesFrag); break; } } private void addFrafment(Fragment f) { FragmentManager manager = getSupportFragmentManager(); FragmentTransaction transaction = manager.beginTransaction(); if (fragment != null) { //隐藏 transaction.hide(fragment); } if (!f.isAdded()) { //isAdded对象有没有别添加过 transaction.add(R.id.con_fragmnet, f); } //显示当前的fragment页面 transaction.show(f); transaction.commit(); fragment = f; } }
MainActivity 布局文件:
<?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:id="@+id/activity_main" android:layout_width="match_parent" android:layout_height="match_parent"> <RadioGroup android:id="@+id/radiog" android:layout_width="match_parent" android:layout_height="65dp" android:layout_alignParentBottom="true" android:orientation="horizontal"> <RadioButton android:id="@+id/ra1" android:layout_width="0dp" android:layout_height="match_parent" android:layout_weight="1" android:button="@null" android:checked="true" android:drawableTop="@drawable/manhua" android:gravity="center" android:onClick="onClick" android:text="漫画" android:textColor="@drawable/ziti_color" /> <RadioButton android:id="@+id/ra2" android:layout_width="0dp" android:layout_height="match_parent" android:layout_weight="1" android:button="@null" android:drawableTop="@drawable/faxian" android:gravity="center" android:onClick="onClick" android:text="发现" android:textColor="@drawable/ziti_color" /> <RadioButton android:id="@+id/ra3" android:layout_width="0dp" android:layout_height="match_parent" android:layout_weight="1" android:button="@null" android:drawableTop="@drawable/shequ" android:gravity="center" android:onClick="onClick" android:text="社区" android:textColor="@drawable/ziti_color" /> <RadioButton android:id="@+id/ra4" android:layout_width="0dp" android:layout_height="match_parent" android:layout_weight="1" android:button="@null" android:drawableTop="@drawable/mes_wo" android:gravity="center" android:onClick="onClick" android:text="我的" android:textColor="@drawable/ziti_color" /> </RadioGroup> <FrameLayout android:id="@+id/con_fragmnet" android:layout_width="match_parent" android:layout_height="match_parent" android:layout_above="@id/radiog"></FrameLayout> </RelativeLayout>布局中用到字体颜色的选择器,还有4中图片的选择器:在drawable中创建
字体的选择器:ziti_color.xml
<?xml version="1.0" encoding="utf-8"?> <selector xmlns:android="http://schemas.android.com/apk/res/android"> <item android:color="@color/huang" android:state_checked="true" /> <item android:color="@color/hei" android:state_checked="false" /> </selector>用到的color颜色在values下的colors.xml文件中自己创建
4中图片的选择器大同小异只写一个作为参考:faxian.xml<selector xmlns:android="http://schemas.android.com/apk/res/android"> <item android:state_checked="true" android:drawable="@drawable/discover_2"/> <item android:state_checked="false" android:drawable="@drawable/discover" /> </selector>
2. 主要的fragment代码和布局文件
public class FaxianFrag extends Fragment { List<String> images = new ArrayList<>(); private List<RecycBean.DataBean.ComicsBean> listComic = new ArrayList<>(); private Banner banner; private TextView gengduo; private RecyclerView rv; @Nullable @Override public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { View view = inflater.inflate(R.layout.faxian_frag, container, false); return view; } @Override public void onActivityCreated(@Nullable Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); inView(); boolean conn = ConnectionUtil.isConn(getContext()); if (!conn) { ConnectionUtil.setNetworkMethod(getContext()); readBannder(); readJson(); } else { inData(); } } private void inView() { banner = (Banner) getView().findViewById(R.id.banner_id); rv = (RecyclerView) getView().findViewById(R.id.recycler_View); gengduo = (TextView) getView().findViewById(R.id.gengduo); gengduo.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { //Intent it = new Intent(getActivity(), GengduoActivity.class); // startActivity(it); } }); } private void inData() { String url1 = "http://api.kkmh.com/v1/topic_new/discovery_list?gender=0&sa_event=eyJwcm9qZWN0Ijoia3VhaWthbl9hcHAiLCJ0aW1lIjoxNDg3ODM5MDM5MzE1LCJwcm9wZXJ0aWVzIjp7IkhvbWVwYWdlVGFiTmFtZSI6IueDremXqCIsIlZDb21tdW5pdHlUYWJOYW1lIjoi54Ot6ZeoIiwiJG9zX3ZlcnNpb24iOiI0LjIuMiIsIkdlbmRlclR5cGUiOiLlpbPniYgiLCJGcm9tRmluZENhdGVnb3J5VGFiTmFtZSI6IuWFqOmDqCIsIklzQXV0b0xvYWQiOmZhbHNlLCIkbGliX3ZlcnNpb24iOiIxLjYuMzQiLCIkbmV0d29ya190eXBlIjoiV0lGSSIsIiR3aWZpIjp0cnVlLCIkbWFudWZhY3R1cmVyIjoic2Ftc3VuZyIsIkZyb21GaW5kVGFiTmFtZSI6IuaOqOiNkCIsIiRzY3JlZW5faGVpZ2h0Ijo1NzYsIkNhdGVnb3J5Ijoi5peg5rOV6I635Y-WIiwiSG9tZXBhZ2VVcGRhdGVEYXRlIjowLCJQcm9wZXJ0eUV2ZW50IjoiUmVhZEZpbmRQYWdlIiwiRmluZFRhYk5hbWUiOiLmjqjojZAiLCJhYnRlc3RfZ3JvdXAiOjQ2LCIkc2NyZWVuX3dpZHRoIjoxMDI0LCJGaW5kQ2F0ZWdvcnlUYWJOYW1lIjoi5YWo6YOoIiwiJG9zIjoiQW5kcm9pZCIsIlRyaWdnZXJQYWdlIjoiSG9tZVBhZ2UiLCIkY2FycmllciI6IkNNQ0MiLCIkbW9kZWwiOiJHVC1QNTIxMCIsIiRhcHBfdmVyc2lvbiI6IjMuOC4xIn0sInR5cGUiOiJ0cmFjayIsImRpc3RpbmN0X2lkIjoiQTo5MDUxMDQyNzYzNzU1MTA5Iiwib3JpZ2luYWxfaWQiOiJBOjkwNTEwNDI3NjM3NTUxMDkiLCJldmVudCI6IlJlYWRGaW5kUGFnZSJ9"; RequestParams params1 = new RequestParams(); params1.setUri(url1); x.http().get(params1, new Callback.CommonCallback<String>() { @Override public void onSuccess(final String result) { if (result != null) { new Thread( new Runnable() { @Override public void run() { boolean exist = isSdCard(); if (exist) { writeBanner(result); } } } ).start(); Gson gson = new Gson(); LunboImage lunboImage = gson.fromJson(result, LunboImage.class); images = new ArrayList<>(); List<LunboImage.DataBean.InfosBean> infos = lunboImage.getData().getInfos(); for (LunboImage.DataBean.InfosBean bean : infos) { List<LunboImage.DataBean.InfosBean.BannersBean> banners = bean.getBanners(); for (LunboImage.DataBean.InfosBean.BannersBean ban : banners) { String pic = ban.getPic(); Log.e("pic", "onSuccess: ++++++++" + pic); images.add(pic); } } //设置banner样式 // banner.setBannerStyle(BannerConfig.NUM_INDICATOR); //设置图片的加载器 banner.setImageLoader(new GliderImageloader()); banner.setDelayTime(2000); //设置图片集合 banner.setImages(images); //banner设置方法全部调用完毕时最后调用 banner.isAutoPlay(true); banner.start(); } } //判断sdcard卡是否挂载 public boolean isSdCard() { Log.e("=====", "isSdCardExist: "); return Environment.getExternalStorageState().equals( Environment.MEDIA_MOUNTED); } //写入文件 private void writeBanner(String str) { try { File file = new File(Environment.getExternalStorageDirectory(), "caBanner.txt"); if (!file.exists()) { file.createNewFile(); } OutputStream fos = new FileOutputStream(file); fos.write(str.getBytes()); Log.i("=====", "writeDataFromInternet: " + str); fos.close(); } catch (IOException e) { e.printStackTrace(); } } @Override public void onError(Throwable ex, boolean isOnCallback) { } @Override public void onCancelled(CancelledException cex) { } @Override public void onFinished() { } }); String url = "http://api.kuaikanmanhua.com/v1/daily/comic_lists/1489334400?since=0&gender=0&sa_event=eyJwcm9qZWN0I"; RequestParams params = new RequestParams(); params.setUri(url); x.http().get(params, new Callback.CommonCallback<String>() { @Override public void onSuccess(final String result) { if (result != null) { new Thread() { @Override public void run() { super.run(); boolean exist = isSdCard(); if (exist) { writeData(result); } } }.start(); Gson gson = new Gson(); RecycBean recycBean = gson.fromJson(result, RecycBean.class); List<RecycBean.DataBean.ComicsBean> comics = recycBean.getData().getComics(); listComic.addAll(comics); GridLayoutManager manager = new GridLayoutManager(getContext(), 2); rv.setLayoutManager(manager); RecyclerViewAdapter adapter = new RecyclerViewAdapter(getContext(), listComic); adapter.setOnItemClickListener(new RecyclerViewListener.OnItemClickListener() { @Override public void OnItemClick(View v, int position) { Intent intent=new Intent(getContext(), WedActivity.class); intent.putExtra("url",listComic.get(position).getUrl()); startActivity(intent); } }); rv.setAdapter(adapter); adapter.notifyDataSetChanged(); } } //判断sdcard卡是否挂载 public boolean isSdCard() { Log.e("=====", "isSdCardExist: "); return Environment.getExternalStorageState().equals( Environment.MEDIA_MOUNTED); } public void writeData(String srt) { try { File file = new File(Environment.getExternalStorageDirectory(), "cacheData.txt"); if (!file.exists()) { file.createNewFile(); } FileOutputStream fos = new FileOutputStream(file); fos.write(srt.getBytes()); fos.close(); } catch (Exception e) { e.printStackTrace(); } } @Override public void onError(Throwable ex, boolean isOnCallback) { } @Override public void onCancelled(CancelledException cex) { } @Override public void onFinished() { } }); } //读取sdcard文件Bannder private void readBannder() { try { File file = new File(Environment.getExternalStorageDirectory(), "caBanner.txt"); FileInputStream is = new FileInputStream(file); byte[] b = new byte[is.available()]; is.read(b); String result = new String(b); System.out.println("读取成功:" + result); Gson gson = new Gson(); LunboImage lunboImage = gson.fromJson(result, LunboImage.class); images = new ArrayList<>(); List<LunboImage.DataBean.InfosBean> infos = lunboImage.getData().getInfos(); for (LunboImage.DataBean.InfosBean bean : infos) { List<LunboImage.DataBean.InfosBean.BannersBean> banners = bean.getBanners(); for (LunboImage.DataBean.InfosBean.BannersBean ban : banners) { String pic = ban.getPic(); Log.e("pic", "onSuccess: ++++++++" + pic); images.add(pic); } } //设置banner样式 banner.setBannerStyle(BannerConfig.NUM_INDICATOR); //设置图片的加载器 banner.setImageLoader(new GliderImageloader()); banner.setDelayTime(2000); //设置图片集合 banner.setImages(images); //banner设置方法全部调用完毕时最后调用 banner.isAutoPlay(true); banner.start(); } catch (Exception e) { e.printStackTrace(); } } //读取sdcard文件数据 private void readJson() { try { File file = new File(Environment.getExternalStorageDirectory(), "cacheData.txt"); FileInputStream is = new FileInputStream(file); byte[] b = new byte[is.available()]; is.read(b); String result = new String(b); System.out.println("读取成功:" + result); Gson gson=new Gson(); RecycBean recycBean = gson.fromJson(result, RecycBean.class); List<RecycBean.DataBean.ComicsBean> comics = recycBean.getData().getComics(); listComic.addAll(comics); GridLayoutManager manager = new GridLayoutManager(getContext(), 2); rv.setLayoutManager(manager); RecyclerViewAdapter adapter = new RecyclerViewAdapter(getContext(), listComic); rv.setAdapter(adapter); adapter.notifyDataSetChanged(); } catch (Exception e) { e.printStackTrace(); } } class GliderImageloader extends ImageLoader { @Override public void displayImage(Context context, Object path, ImageView imageView) { //Glide 加载图片简单用法 Glide.with(context).load(path).into(imageView); } } }fragment的布局:
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="match_parent" android:layout_height="match_parent"> <com.youth.banner.Banner android:id="@+id/banner_id" android:layout_width="match_parent" android:layout_height="170dp"></com.youth.banner.Banner> <LinearLayout android:layout_width="match_parent" android:layout_height="105dp" android:orientation="horizontal"> <ImageView android:layout_width="0dp" android:layout_height="match_parent" android:layout_weight="1" android:src="@drawable/paihang"/> <ImageView android:layout_width="0dp" android:layout_height="match_parent" android:layout_weight="1" android:src="@drawable/xinzuo"/> <ImageView android:layout_width="0dp" android:layout_weight="1" android:layout_height="match_parent" android:src="@drawable/wanjie"/> <ImageView android:layout_width="0dp" android:layout_weight="1" android:layout_height="match_parent" android:src="@drawable/fenlei"/> </LinearLayout> <LinearLayout android:layout_width="match_parent" android:layout_height="35dp" android:layout_marginTop="6dp" android:orientation="horizontal"> <TextView android:layout_width="wrap_content" android:layout_height="match_parent" android:text="本周推荐" android:textSize="18sp"/> <TextView android:id="@+id/gengduo" android:layout_width="wrap_content" android:layout_height="match_parent" android:layout_marginLeft="245dp" android:text="更多" android:gravity="center" android:textSize="18sp"/> <ImageView android:layout_width="15dp" android:layout_height="match_parent" android:layout_marginLeft="5dp" android:src="@drawable/ww1"/> </LinearLayout> <android.support.v7.widget.RecyclerView android:id="@+id/recycler_View" android:layout_width="match_parent" android:layout_height="match_parent" /> </LinearLayout>//点击更多加载频道,自己实现即可
//和fragment相关的适配器,网络的判断等。。都在一下代码
(1)见一个判断网络的工具类
public class ConnectionUtil { /* * 判断网络连接是否已开 *true 已打开 false 未打开 * */ public static boolean isConn(Context context) { boolean bisConnFlag = false; ConnectivityManager conManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo network = conManager.getActiveNetworkInfo(); if (network != null) { bisConnFlag = conManager.getActiveNetworkInfo().isAvailable(); } return bisConnFlag; } /* * 打开设置网络界面 * */ public static void setNetworkMethod(final Context context){ //提示对话框 AlertDialog.Builder builder=new AlertDialog.Builder(context); builder.setTitle("网络设置提示").setMessage("网络连接不可用,是否进行设置?").setPositiveButton("设置", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { // TODO Auto-generated method stub Intent intent=null; //判断手机系统的版本 即API大于10 就是3.0或以上版本 if(android.os.Build.VERSION.SDK_INT>10){ intent = new Intent(android.provider.Settings.ACTION_WIRELESS_SETTINGS); }else{ intent = new Intent(); ComponentName component = new ComponentName("com.android.settings","com.android.settings.WirelessSettings"); intent.setComponent(component); intent.setAction("android.intent.action.VIEW"); } context.startActivity(intent); } }).setNegativeButton("取消", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { // TODO Auto-generated method stub dialog.dismiss(); } }).show(); } }
用到的RecyclerView
public class RecyclerViewAdapter extends RecyclerView.Adapter<RecyclerViewAdapter.ViewHolder> implements View.OnClickListener, View.OnLongClickListener { private Context context; private List<RecycBean.DataBean.ComicsBean> list; private RecyclerViewListener.OnItemClickListener listener; private RecyclerViewListener.OnItemLongClickListener longListener; public void setOnItemClickListener(RecyclerViewListener.OnItemClickListener listener){ this.listener=listener; } public void setOnLongItemClickListener(RecyclerViewListener.OnItemLongClickListener longListener){ this.longListener=longListener; } public RecyclerViewAdapter(Context context, List<RecycBean.DataBean.ComicsBean> list) { this.context = context; this.list = list; } @Override public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { View view = View.inflate(context, R.layout.recyc_layout, null); ViewHolder holder = new ViewHolder(view); view.setOnClickListener(this); view.setOnLongClickListener(this); return holder; } @Override public void onBindViewHolder(ViewHolder holder, int position) { holder.itemView.setTag(position); RecycBean.DataBean.ComicsBean recycBean = list.get(position); Glide.with(context).load(recycBean.getCover_image_url()).into(holder.imagesurl); holder.label_text.setText(recycBean.getLabel_text()); holder.label_title.setText(recycBean.getTitle()); } @Override public int getItemCount() { return list.size(); } @Override public void onClick(View v) { if (listener!=null){ listener.OnItemClick(v, (Integer) v.getTag()); } } @Override public boolean onLongClick(View v) { if (longListener!=null){ longListener.OnLongItemClick(v, (Integer) v.getTag()); } return false; } class ViewHolder extends RecyclerView.ViewHolder { private ImageView imagesurl; private TextView label_text; private TextView label_title; public ViewHolder(View itemView) { super(itemView); imagesurl = (ImageView) itemView.findViewById(R.id.imagesurl); label_text = (TextView) itemView.findViewById(R.id.label_text); label_title = (TextView) itemView.findViewById(R.id.label_title); } } }相关布局:
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical"> <ImageView android:id="@+id/imagesurl" android:layout_width="180dp" android:layout_height="100dp" /> <TextView android:id="@+id/label_text" android:layout_width="wrap_content" android:layout_height="55dp" android:textSize="20sp" android:textColor="#000"/> <TextView android:id="@+id/label_title" android:layout_width="wrap_content" android:layout_height="40dp" android:textSize="16sp" android:textColor="#9f9c9c"/> </LinearLayout>
//用到一个接口回掉的类:
public class RecyclerViewListener { public interface OnItemClickListener{ void OnItemClick(View v,int position); } public interface OnItemLongClickListener{ void OnLongItemClick(View v,int position); } }//点击条目跳转加载WedView
public class WedActivity extends AppCompatActivity { private WebView wv; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_wed); wv = (WebView) findViewById(R.id.wed_url); Intent intent=getIntent(); String uri = intent.getStringExtra("url"); wv.loadUrl(uri); } }
布局文件:
<?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:id="@+id/activity_wed" android:layout_width="match_parent" android:layout_height="match_parent" tools:context="huanghui.bawei.com.yuekaoblianxi.WedActivity"> <WebView android:id="@+id/wed_url" android:layout_width="match_parent" android:layout_height="match_parent"></WebView> </RelativeLayout>