activity_main “Drawer && Tablayout”
导入依赖
implementation ‘com.android.support:design:28.0.0’
implementation project(’:library’)
implementation ‘com.nostra13.universalimageloader:universal-image-loader:1.9.5’
implementation ‘com.google.code.gson:gson:2.8.5’
implementation ‘com.youth.banner:banner:1.4.10’
implementation ‘com.github.andyoom:draggrid:v1.0.1’
implementation ‘com.android.support:recyclerview-v7:28.0.0’
package com.example.myapp;
import android.support.design.widget.TabLayout;
import android.support.v4.view.ViewPager;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Gravity;
import android.view.MenuItem;
public class MainActivity extends AppCompatActivity {
private DrawerLayout layout;
private TabLayout tabLayout;
private ViewPager viewPager;
private LeftAdapter adapter;
private ActionBarDrawerToggle toggle;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (savedInstanceState==null){
getSupportFragmentManager().beginTransaction()
.add(R.id.left_drawer,new LeftFragment())
.commit();
}
layout = findViewById(R.id.drawer);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
toggle = new ActionBarDrawerToggle(this,layout,R.string.open,R.string.close);
layout.addDrawerListener(toggle);
toggle.syncState();
viewPager = findViewById(R.id.viewPager_one);
tabLayout = findViewById(R.id.tabLayout_one);
viewPager.setAdapter(new LeftAdapter(getSupportFragmentManager()));
tabLayout.setupWithViewPager(viewPager);
}
//点击跳转
public void showPage(int i) {
viewPager.setCurrentItem(i);
layout.closeDrawer(Gravity.START);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
if (toggle.onOptionsItemSelected(item)){
return true;
}
return super.onOptionsItemSelected(item);
}
}
Activity_main 主页面布局
<?xml version="1.0" encoding="utf-8"?>
<android.support.v4.widget.DrawerLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/drawer"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<android.support.design.widget.TabLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/tabLayout_one"
android:layout_alignParentBottom="true"
/>
<android.support.v4.view.ViewPager
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="@+id/viewPager_one"
android:layout_above="@id/tabLayout_one"
/>
</RelativeLayout>
<FrameLayout
android:layout_width="180dp"
android:layout_height="match_parent"
android:id="@+id/left_drawer"
android:layout_gravity="start"
android:background="@color/design_default_color_primary"
></FrameLayout>
</android.support.v4.widget.DrawerLayout>
主页面图片
NetUtil 工具类
package com.example.myapp;
import android.annotation.SuppressLint;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import com.google.gson.Gson;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
public class NetUtil {
private static NetUtil instance;
private Gson gson;
public static NetUtil getInstance() {
if (instance==null){
instance = new NetUtil();
}
return instance;
}
public NetUtil(){
gson = new Gson();
}
public interface CallBack<E>{
void onsuccess(E e);
}
@SuppressLint("StaticFieldLeak")
public void getRequest(String urlstr, final Class clazz, final CallBack callBack){
new AsyncTask<String,Void,Object>(){
@Override
protected Object doInBackground(String... strings) {
return getRequest(strings[0],clazz);
}
@Override
protected void onPostExecute(Object o) {
callBack.onsuccess(o);
}
}.execute(urlstr);
}
public String getRequest(String urlstr){
String result = "";
try {
URL url = new URL(urlstr);
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestMethod("GET");
urlConnection.setConnectTimeout(5000);
urlConnection.setReadTimeout(5000);
if (urlConnection.getResponseCode()==200){
result = stream2String(urlConnection.getInputStream());
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return result;
}
public <E> E getRequest(String urlstr,Class clazz){
return (E) gson.fromJson(getRequest(urlstr),clazz);
}
private String stream2String(InputStream inputStream) throws IOException {
InputStreamReader isr = new InputStreamReader(inputStream);
BufferedReader br = new BufferedReader(isr);
StringBuffer sb = new StringBuffer();
for (String tmp = br.readLine();tmp!=null;tmp=br.readLine()){
sb.append(tmp);
}
return sb.toString();
}
public interface ImageCallBack{
void onsuccess(Bitmap bitmap);
}
@SuppressLint("StaticFieldLeak")
public void getBitmap(String imageurl, final int width, final int height, final ImageCallBack imageCallBack){
new AsyncTask<String,Void,Bitmap>(){
@Override
protected Bitmap doInBackground(String... strings) {
return getBitmap(strings[0],width,height);
}
@Override
protected void onPostExecute(Bitmap bitmap) {
imageCallBack.onsuccess(bitmap);
}
}.execute(imageurl);
}
public Bitmap getBitmap(String imageurl,int width,int height){
//第一次加载宽高信息
BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeFile(imageurl,options);
//根据图片原始宽高和请求宽高 计算采样率
options.inSampleSize = Math.max(options.outWidth / width, options.outHeight / height);
options.inJustDecodeBounds = false;
return BitmapFactory.decodeFile(imageurl,options);
}
}
侧拉 LeftFragment
package com.example.myapp;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.content.CursorLoader;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ListView;
public class LeftFragment extends Fragment {
private ListView listView;
private final int REQUEST_SUCCESS = 100;
private LeftDrawerAdapter adapter;
@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
return inflater.inflate(R.layout.left_drawer,container,false);
}
@Override
public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
listView = view.findViewById(R.id.list);
adapter = new LeftDrawerAdapter(getActivity());
listView.setAdapter(adapter);
//点击跳转
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
//图片
if (position==0){
Intent intent = new Intent(Intent.ACTION_PICK);
intent.setType("image/*");
startActivityForResult(intent,REQUEST_SUCCESS);
}
((MainActivity)getActivity()).showPage(position-1);
}
});
super.onViewCreated(view, savedInstanceState);
}
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode==REQUEST_SUCCESS && resultCode==getActivity().RESULT_OK){
Uri uri = data.getData();
//调用获取图片的方法;
progressImage(url2path(uri));
}
super.onActivityResult(requestCode, resultCode, data);
}
//获取二次采样图片
private void progressImage(String imageurl) {
int size = getResources().getDimensionPixelSize(R.dimen.leftIconSize);
NetUtil.getInstance().getBitmap(imageurl, size, size, new NetUtil.ImageCallBack() {
@Override
public void onsuccess(Bitmap bitmap) {
adapter.setIconBitmap(bitmap);
}
});
}
//获取图片路径
private String url2path(Uri uri) {
String[] proj = {MediaStore.Images.Media.DATA};
CursorLoader loader = new CursorLoader(getActivity(), uri, proj, null, null, null);
Cursor cursor = loader.loadInBackground();
int columnIndexOrThrow = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToNext();
return cursor.getString(columnIndexOrThrow);
}
}
适配器 LeftDrawerAdapter && LeftAdapter
package com.example.myapp;
import android.content.Context;
import android.graphics.Bitmap;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;
public class LeftDrawerAdapter extends BaseAdapter {
private String[] names = new String[]{
"首页","图片","我的"
};
private Context context;
private Bitmap bitmap;
private final int ITEM_COUNT = 2;
private final int IMAGE_TYPE = 0;
private final int TEXT_TYPE = 1;
//传递图片的方法
public void setIconBitmap(Bitmap bitmap){
this.bitmap=bitmap;
notifyDataSetChanged();
}
public LeftDrawerAdapter(Context context) {
this.context = context;
}
@Override
public int getCount() {
return names.length + 1;
}
@Override
public String getItem(int position) {
if (position==0){
return null;
}
return names[position - 1 ];
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public int getItemViewType(int position) {
return position==0 ? IMAGE_TYPE:TEXT_TYPE;
}
@Override
public int getViewTypeCount() {
return ITEM_COUNT;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder viewHolder;
if (convertView==null){
convertView = LayoutInflater.from(context).inflate(getItemViewType(position)==IMAGE_TYPE ? R.layout.left_drawer_image:R.layout.left_drawer_text,parent,false);
viewHolder = new ViewHolder(convertView);
}else{
viewHolder = (ViewHolder) convertView.getTag();
}
if (getItemViewType(position)==TEXT_TYPE){
viewHolder.bindData(getItem(position));
}else{
if (bitmap!=null){
viewHolder.bindIcon(bitmap);
}
}
return convertView;
}
class ViewHolder{
ImageView image;
TextView text;
public ViewHolder(View itemView) {
image = itemView.findViewById(R.id.icon);
text = itemView.findViewById(R.id.text);
itemView.setTag(this);
}
public void bindData(String item) {
text.setText(item);
}
public void bindIcon(Bitmap bitmap) {
//图片赋值
image.setImageBitmap(bitmap);
}
}
}
*****************************************************************************************
package com.example.myapp;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
public class LeftAdapter extends FragmentPagerAdapter {
private String[] names = new String[]{
"首页","图片","我的"
};
public LeftAdapter(FragmentManager fm) {
super(fm);
}
@Override
public Fragment getItem(int i) {
switch (i){
case 0:
return new FragmentHome();
case 1:
return new FragmentImage();
case 2:
return new FragmentMine();
}
return null;
}
@Override
public int getCount() {
return names.length;
}
@Nullable
@Override
public CharSequence getPageTitle(int position) {
return names[position];
}
}
子布局 left_drawer
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
xmlns:app="http://schemas.android.com/apk/res-auto">
<ListView
android:id="@+id/list"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintBottom_toBottomOf="parent"
></ListView>
</android.support.constraint.ConstraintLayout>
子布局 home
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
xmlns:app="http://schemas.android.com/apk/res-auto">
<ImageView
android:id="@+id/icon"
android:layout_width="150dp"
android:layout_height="150dp"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintBottom_toBottomOf="parent"
/>
<TextView
android:id="@+id/description"
android:layout_width="0dp"
android:layout_height="wrap_content"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toLeftOf="@id/icon"
android:text="aaaaaa"
/>
<TextView
android:id="@+id/title"
android:layout_width="0dp"
android:layout_height="wrap_content"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toLeftOf="@id/icon"
android:text="aaaaaa"
/>
</android.support.constraint.ConstraintLayout>
侧拉 image视图 && text视图
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
xmlns:app="http://schemas.android.com/apk/res-auto">
<ImageView
android:id="@+id/icon"
android:layout_width="150dp"
android:layout_height="150dp"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
android:src="@mipmap/ic_launcher"
/>
</android.support.constraint.ConstraintLayout>
***********************************************************************************
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
xmlns:app="http://schemas.android.com/apk/res-auto">
<TextView
android:id="@+id/text"
android:layout_width="0dp"
android:layout_height="wrap_content"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintBottom_toBottomOf="parent"
android:textSize="24sp"
android:text="TEXT"
android:gravity="center"
/>
</android.support.constraint.ConstraintLayout>
FragmentHome
package com.example.myapp;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ListView;
import android.widget.Toast;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshListView;
public class FragmentHome extends Fragment {
private PullToRefreshListView refreshListView;
private PullAdapter adapter;
private int mPage = 1;
private String url ="http://api.tianapi.com/military/?key=605fa0a929c8d8b116424df0510c6b2a&num=10";
@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
return inflater.inflate(R.layout.frag_home,container,false);
}
@Override
public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
mPage=1;
refreshListView = view.findViewById(R.id.p_list);
adapter = new PullAdapter(getActivity());
refreshListView.setAdapter(adapter);
refreshListView.setMode(PullToRefreshBase.Mode.BOTH);
refreshListView.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener2<ListView>() {
@Override
public void onPullDownToRefresh(PullToRefreshBase<ListView> refreshView) {
mPage=1;
initData();
}
@Override
public void onPullUpToRefresh(PullToRefreshBase<ListView> refreshView) {
initData();
}
});
initData();
super.onViewCreated(view, savedInstanceState);
}
private void initData() {
NetUtil.getInstance().getRequest(url, UserBean.class, new NetUtil.CallBack<UserBean>() {
@Override
public void onsuccess(UserBean o) {
if (o==null||!o.getSuccess()){
Toast.makeText(getActivity(),"请求错误",Toast.LENGTH_LONG).show();
refreshListView.onRefreshComplete();
return;
}
UserDao.getDao(getActivity()).deleteall();
UserDao.getDao(getActivity()).addall(o.getNewslist());
if (mPage==1){
// adapter.setMdatas(o.getNewslist());
adapter.setMdatas(UserDao.getDao(getActivity()).select());
}else {
//adapter.addMdatas(o.getNewslist());
adapter.addMdatas(UserDao.getDao(getActivity()).select());
}
mPage++;
refreshListView.onRefreshComplete();
}
});
}
}
pullAdapter
package com.example.myapp;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import com.nostra13.universalimageloader.core.ImageLoader;
import java.util.ArrayList;
import java.util.List;
public class PullAdapter extends BaseAdapter {
private List<UserBean.NewslistBean> mdatas;
private Context context;
public PullAdapter(Context context) {
this.context = context;
mdatas = new ArrayList<>();
}
public void setMdatas(List<UserBean.NewslistBean> datas) {
mdatas.clear();
if (datas!=null){
mdatas.addAll(datas);
}
notifyDataSetChanged();
}
public void addMdatas(List<UserBean.NewslistBean> datas) {
if (datas!=null){
mdatas.addAll(datas);
}
notifyDataSetChanged();
}
@Override
public int getCount() {
return mdatas.size();
}
@Override
public UserBean.NewslistBean getItem(int position) {
return mdatas.get(position);
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder viewHolder;
if (convertView==null){
convertView = LayoutInflater.from(context).inflate(R.layout.home,parent,false);
viewHolder = new ViewHolder(convertView);
}else {
viewHolder = (ViewHolder) convertView.getTag();
}
viewHolder.bindData(getItem(position));
return convertView;
}
class ViewHolder{
TextView description;
TextView title;
ImageView icon;
public ViewHolder(View itemView) {
description = itemView.findViewById(R.id.description);
title = itemView.findViewById(R.id.title);
icon = itemView.findViewById(R.id.icon);
itemView.setTag(this);
}
public void bindData(UserBean.NewslistBean item) {
description.setText(item.getDescription());
title.setText(item.getTitle());
ImageLoader.getInstance().displayImage(item.getPicUrl(),icon);
}
}
}
FragmentHome userbean类
package com.example.myapp;
import java.util.List;
public class UserBean {
/**
* code : 200
* msg : success
* newslist : [{"ctime":"2018-11-20 11:40","title":"伊朗的\u201c执念\u201d:全力发展\u201c非对称\u201d战力","description":"军事图集","picUrl":"https://img1.utuku.china.com/162x110/mili/20181120/05e58e66-912b-4de4-b754-07cf872f597b.jpg","url":"https://military.china.com/important/11132797/20181120/34464063.html"},{"ctime":"2018-11-20 14:57","title":"港媒:美军里根号航母将于21日访问香港","description":"军事图集","picUrl":"https://img3.utuku.china.com/162x110/mili/20181120/224d479c-de62-4392-bf81-351fc3722119.jpg","url":"https://military.china.com/important/11132797/20181120/34466951.html"},{"ctime":"2018-11-20 15:16","title":"美媒:双航母编队军演后 里根号航母编队进入中国南海","description":"军事图集","picUrl":"https://img0.utuku.china.com/162x110/mili/20181120/59da4899-526c-4ce5-b501-c6592fa2dfb8.jpg","url":"https://military.china.com/important/11132797/20181120/34467303.html"},{"ctime":"2018-11-20 15:23","title":"台媒评美军里根号航母进南海 刻意强调在台选举前夕","description":"军事图集","picUrl":"https://img2.utuku.china.com/162x110/mili/20181120/3561bc9d-6eca-4a96-90f9-bff93e4bf15f.png","url":"https://military.china.com/important/11132797/20181120/34467364.html"},{"ctime":"2018-11-20 15:39","title":"外媒:美国正在退离世界舞台 而"中国时刻"才刚刚开始","description":"军事图集","picUrl":"https://img0.utuku.china.com/162x110/mili/20181120/efe022c4-b936-40f6-9ff4-f54d7798850d.jpg","url":"https://military.china.com/important/11132797/20181120/34467600.html"},{"ctime":"2018-11-21 07:31","title":"美军担忧到2035年将无力阻止中国了!","description":"军事图集","picUrl":"https://img0.utuku.china.com/162x110/mili/20181121/989e837c-fd4e-4f39-8402-ee63ebd37cf9.jpg","url":"https://military.china.com/important/11132797/20181121/34470039.html"},{"ctime":"2018-11-21 07:42","title":"美海航缺少假想敌机?美军官竟称可派飞行员偷盗歼20","description":"军事图集","picUrl":"https://img0.utuku.china.com/162x110/mili/20181121/b63a5b44-04e3-44d5-9a9b-5bcb4300b9c2.jpg","url":"https://military.china.com/important/11132797/20181121/34470249.html"},{"ctime":"2018-11-21 07:49","title":"澳媒疯狂臆测\u201c中国云间谍\u201d 外交部这样回应","description":"军事图集","picUrl":"https://img0.utuku.china.com/162x110/mili/20181121/16f62b27-4e48-4309-bfc6-fc83043b1228.jpg","url":"https://military.china.com/important/11132797/20181121/34470265.html"},{"ctime":"2018-11-21 07:57","title":"达赖主张西藏和中国要找到共存共荣的方法 外交部回应","description":"军事图集","picUrl":"https://img0.utuku.china.com/162x110/mili/20181121/69bfc595-be4f-452d-9f0e-4bbe2727be53.jpg","url":"https://military.china.com/important/11132797/20181121/34470305.html"},{"ctime":"2018-11-21 08:01","title":"欧盟对中资筑起\u201c防火墙\u201d?","description":"军事图集","picUrl":"https://img3.utuku.china.com/162x110/mili/20181121/336d88b5-2ab2-48a4-a769-260c7175ad17.jpg","url":"https://military.china.com/important/11132797/20181121/34470328.html"}]
*/
private int code;
private String msg;
private List<NewslistBean> newslist;
// 请求码
private final int SUCCESS = 200;
public boolean getSuccess(){
return code==SUCCESS;
}
public int getCode() {
return code;
}
public void setCode(int code) {
this.code = code;
}
public String getMsg() {
return msg;
}
public void setMsg(String msg) {
this.msg = msg;
}
public List<NewslistBean> getNewslist() {
return newslist;
}
public void setNewslist(List<NewslistBean> newslist) {
this.newslist = newslist;
}
public static class NewslistBean {
/**
* ctime : 2018-11-20 11:40
* title : 伊朗的“执念”:全力发展“非对称”战力
* description : 军事图集
* picUrl : https://img1.utuku.china.com/162x110/mili/20181120/05e58e66-912b-4de4-b754-07cf872f597b.jpg
* url : https://military.china.com/important/11132797/20181120/34464063.html
*/
private String ctime;
private String title;
private String description;
private String picUrl;
private String url;
public NewslistBean(String title, String description, String picUrl) {
this.title = title;
this.description = description;
this.picUrl = picUrl;
}
public String getCtime() {
return ctime;
}
public void setCtime(String ctime) {
this.ctime = ctime;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getPicUrl() {
return picUrl;
}
public void setPicUrl(String picUrl) {
this.picUrl = picUrl;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
}
}
Fragmentimage轮播图
package com.example.myapp;
import android.content.Context;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import com.youth.banner.Banner;
import com.youth.banner.BannerConfig;
import com.youth.banner.loader.ImageLoaderInterface;
import java.util.ArrayList;
import java.util.List;
public class FragmentImage extends Fragment {
private String imageUrl = "https://api.tianapi.com/wxnew/?key=605fa0a929c8d8b116424df0510c6b2a&num=6&page=1";
private Banner banner;
@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
return inflater.inflate(R.layout.frag_image,container,false);
}
@Override
public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
banner = view.findViewById(R.id.banner);
//设置banner样式
banner.setBannerStyle(BannerConfig.CIRCLE_INDICATOR_TITLE_INSIDE);
//设置图片加载器
banner.setImageLoader(new ImageLoaderInterface<ImageView>() {
@Override
public void displayImage(Context context, Object path, ImageView imageView) {
ImageBean.NewslistBean bean = (ImageBean.NewslistBean) path;
com.nostra13.universalimageloader.core.ImageLoader.getInstance().displayImage(
bean.getPicUrl(),imageView
);
}
@Override
public ImageView createImageView(Context context) {
ImageView imageView = new ImageView(context);
imageView.setScaleType(ImageView.ScaleType.FIT_XY);
return imageView;
}
});
initData();
super.onViewCreated(view, savedInstanceState);
}
public void initData(){
NetUtil.getInstance().getRequest(imageUrl, ImageBean.class, new NetUtil.CallBack<ImageBean>() {
@Override
public void onsuccess(ImageBean o) {
//设置图片集合
banner.setImages(o.getNewslist());
banner.setBannerTitles(getTitles(o));
//banner 方法调用完 执行
banner.start();
}
});
}
private List<String> getTitles(ImageBean o) {
List<String> list = new ArrayList<>();
for (ImageBean.NewslistBean banner :o.getNewslist()){
list.add(banner.getTitle());
}
return list;
}
}
轮播图 布局
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
xmlns:app="http://schemas.android.com/apk/res-auto">
<com.youth.banner.Banner
android:layout_width="match_parent"
android:layout_height="240dp"
android:id="@+id/banner"
app:indicator_width="8dp"
app:indicator_height="8dp"
app:indicator_drawable_selected="@drawable/shape_sel"
app:indicator_drawable_unselected="@drawable/shape_nor"
/>
</android.support.constraint.ConstraintLayout>
*************************************************************
values下创建dimens
<?xml version="1.0" encoding="utf-8"?>
<resources>
<dimen name="leftIconSize">100dp</dimen>
</resources>
轮播图小圆点选中状态
selector
<?xml version="1.0" encoding="utf-8"?>
<resources>
<dimen name="leftIconSize">100dp</dimen>
</resources>
shape_sel
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="oval"
>
<size
android:width="8dp"
android:height="8dp"
/>
<solid
android:color="#fffccc"
/>
</shape>
shape_nor
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="oval"
>
<size
android:width="8dp"
android:height="8dp"
/>
<solid
android:color="#f00"
/>
</shape>
频道管理 FragmentMine
频道管理布局
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
xmlns:app="http://schemas.android.com/apk/res-auto">
<TextView
android:id="@+id/text"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="+"
android:textSize="40dp"
android:layout_marginRight="5dp"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintBottom_toTopOf="@+id/viewpager"
/>
<android.support.design.widget.TabLayout
android:id="@+id/tab"
android:layout_width="0dp"
android:layout_height="60dp"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintRight_toLeftOf="@+id/text"
app:tabMode="scrollable"
/>
<android.support.v4.view.ViewPager
android:id="@+id/viewpager"
android:layout_width="0dp"
android:layout_height="0dp"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintTop_toBottomOf="@+id/tab"
/>
</android.support.constraint.ConstraintLayout>
package com.example.myapp;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import com.andy.library.ChannelActivity;
import com.andy.library.ChannelBean;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;
import static com.andy.library.ChannelActivity.REQUEST_CODE;
import static com.andy.library.ChannelActivity.RESULT_JSON_KEY;
public class FragmentMine extends Fragment {
private TextView textView;
private TabLayout tabLayout;
private ViewPager viewPager;
private List<ChannelBean> channelBeans=new ArrayList<>();
private List<Fragment> fragments=new ArrayList<>();
private String jsonStr="";
private Gson gson;
@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
return inflater.inflate(R.layout.frag_mine, container, false);
}
@Override
public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
textView = view.findViewById(R.id.text);
tabLayout = view.findViewById(R.id.tab);
viewPager = view.findViewById(R.id.viewpager);
initData();
super.onViewCreated(view, savedInstanceState);
}
private void initData() {
channelBeans.add(new ChannelBean("热点", true));
channelBeans.add(new ChannelBean("军事", true));
channelBeans.add(new ChannelBean("八卦", true));
channelBeans.add(new ChannelBean("游戏", true));
channelBeans.add(new ChannelBean("宠物", true));
channelBeans.add(new ChannelBean("汽车", true));
channelBeans.add(new ChannelBean("热卖", true));
channelBeans.add(new ChannelBean("外卖", true));
channelBeans.add(new ChannelBean("条目1", true));
channelBeans.add(new ChannelBean("条目2", true));
channelBeans.add(new ChannelBean("条目3", false));
channelBeans.add(new ChannelBean("条目4", false));
channelBeans.add(new ChannelBean("条目5", false));
channelBeans.add(new ChannelBean("条目6", false));
channelBeans.add(new ChannelBean("条目7", false));
channelBeans.add(new ChannelBean("条目8", false));
fragments.add(new AFragment());
fragments.add(new BFragment());
fragments.add(new CFragment());
fragments.add(new BFragment());
fragments.add(new AFragment());
fragments.add(new BFragment());
fragments.add(new CFragment());
fragments.add(new BFragment());
fragments.add(new CFragment());
fragments.add(new AFragment());
fragments.add(new BFragment());
fragments.add(new AFragment());
fragments.add(new AFragment());
fragments.add(new AFragment());
fragments.add(new AFragment());
fragments.add(new AFragment());
for(int i=0;i<channelBeans.size();i++){
if(channelBeans.get(i).isSelect()){
tabLayout.addTab(tabLayout.newTab().setText(channelBeans.get(i).getName()));
}
}
//viewpager设置适配器
viewPager.setAdapter(new FragmentPagerAdapter(getChildFragmentManager()) {
@Override
public Fragment getItem(int i) {
return fragments.get(i);
}
@Override
public int getCount() {
int count=0;//返回选中的条目数量
for(int i=0;i<channelBeans.size();i++){
if(channelBeans.get(i).isSelect()){
count++;
}
}
return count;
}
@Nullable
@Override
public CharSequence getPageTitle(int position) {
return channelBeans.get(position).getName();
}
});
tabLayout.setupWithViewPager(viewPager);
textView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
gson=new Gson();//进行gson解析
String jsonArray = gson.toJson(channelBeans);
Intent intent = new Intent(getActivity(),ChannelActivity.class);
intent.putExtra(RESULT_JSON_KEY, jsonArray);
startActivityForResult(intent, REQUEST_CODE);
}
});
}
@Override
public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(requestCode==REQUEST_CODE&&resultCode==ChannelActivity.RESULT_CODE){
//得到栏目管理的结果
jsonStr=data.getStringExtra(RESULT_JSON_KEY);
tabLayout.removeAllTabs();//清空之前所有的栏目
Type type=new TypeToken<List<ChannelBean>>(){}.getType();
channelBeans=gson.fromJson(jsonStr,type);
//循环存入
for(int i=0;i<channelBeans.size();i++){
if(channelBeans.get(i).isSelect()){
try {
tabLayout.addTab(tabLayout.newTab().setText(channelBeans.get(i).getName()));
}catch (Exception e){
}
}
}
//viewpager适配器刷新
viewPager.getAdapter().notifyDataSetChanged();
}
}
}
创建三个 ABC Fragment
package com.example.myapp;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
public class BFragment extends Fragment {
@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
return inflater.inflate(R.layout.bfragment,container,false);
}
}
全局适配类
package com.example.myapp;
import android.app.Application;
import android.graphics.Bitmap;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.ImageLoaderConfiguration;
public class App extends Application {
@Override
public void onCreate() {
ImageLoader.getInstance().init(new ImageLoaderConfiguration.Builder(this)
.diskCacheSize(50*1024*1024)
.memoryCacheSizePercentage(10)
.defaultDisplayImageOptions(new DisplayImageOptions.Builder()
.bitmapConfig(Bitmap.Config.RGB_565)
.cacheOnDisk(true)
.cacheInMemory(true)
.showImageOnLoading(R.mipmap.ic_launcher)
.showImageOnFail(R.mipmap.ic_launcher)
.showImageForEmptyUri(R.mipmap.ic_launcher)
.build()
)
.build()
);
super.onCreate();
}
}
数据库
package com.example.myapp;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
public class Mysqlite extends SQLiteOpenHelper {
public Mysqlite( Context context) {
super(context, "user.db", null, 1);
}
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("create table users(id integer primary key autoincrement," +
"title text," +
"description text," +
"picUrl text)");
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
}
DAO 层
package com.example.myapp;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import java.util.ArrayList;
import java.util.List;
public class UserDao {
private static UserDao dao;
private final SQLiteDatabase database;
public UserDao(Context context) {
database = new Mysqlite(context).getWritableDatabase();
}
public static UserDao getDao(Context context) {
if (dao==null){
dao = new UserDao(context);
}
return dao;
}
public void addall(List<UserBean.NewslistBean> newslist) {
try{
database.beginTransaction();
for (UserBean.NewslistBean bean: newslist
) {
add(bean);
}
database.setTransactionSuccessful();
}finally {
database.endTransaction();
}
}
private void add(UserBean.NewslistBean bean) {
ContentValues values = new ContentValues();
values.put("title",bean.getTitle());
values.put("description",bean.getDescription());
values.put("picUrl",bean.getPicUrl());
database.insert("users",null,values);
}
public void deleteall() {
database.delete("users",null,null);
}
public List<UserBean.NewslistBean> select(){
List<UserBean.NewslistBean> beans = new ArrayList<>();
Cursor query = database.query("users", null, null, null, null, null, null);
while (query.moveToNext()){
String title = query.getString(query.getColumnIndex("title"));
String description = query.getString(query.getColumnIndex("description"));
String picUrl = query.getString(query.getColumnIndex("picUrl"));
beans.add(new UserBean.NewslistBean(title,description,picUrl));
}
return beans;
}
}