侧拉
代码
1提取的基类
1.1Activity的基类
package com.example.zonghelianxi02.ui.activity;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
public abstract class BaseActivity extends AppCompatActivity {
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(getLayoutResId());
//初始化view
initView(savedInstanceState);
//加载数据
initData();
}
protected abstract void initData();
protected abstract void initView(Bundle savedInstanceState);
protected abstract int getLayoutResId();
}
1.2.fragment的基类
package com.example.zonghelianxi02.ui.fragment;
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 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);
//初始化view
initView(view);
//加载数据
initData();
}
protected abstract void initData();
protected abstract void initView(View view);
protected abstract int getLayoutResId();
}
2.MainActivity主页面 包括点击侧拉条目跳到不同的fragment和底部Tablayout和fragment切换
package com.example.zonghelianxi02.ui.activity;
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;
import com.example.zonghelianxi02.R;
import com.example.zonghelianxi02.ui.adaper.MainAdaper;
import com.example.zonghelianxi02.ui.fragment.LeftFragment;
public class MainActivity extends BaseActivity {
private DrawerLayout drawerLayout;
private ActionBarDrawerToggle toggle;
private ViewPager viewPager;
@Override
protected void initData() {
}
@Override
protected void initView(Bundle savedInstanceState) {
//当savedInstanceState为空时
if (savedInstanceState==null){
getSupportFragmentManager().beginTransaction()
.add(R.id.left_deawer,new LeftFragment())
.commit();
}
//显示侧边栏
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
//获取资源id
drawerLayout = findViewById(R.id.drawer_layout);
toggle = new ActionBarDrawerToggle(this,drawerLayout,R.string.open,R.string.close);
drawerLayout.addDrawerListener(toggle);
toggle.syncState();
//获取资源id
viewPager = findViewById(R.id.contenes);
viewPager.setAdapter(new MainAdaper(getSupportFragmentManager()));
//获取tablayout的id
TabLayout tabLayout = findViewById(R.id.bottom_indicator);
tabLayout.setupWithViewPager(viewPager);
}
//侧拉右上角图标可点击
@Override
public boolean onOptionsItemSelected(MenuItem item) {
if(toggle.onOptionsItemSelected(item)){
return true;
}
return super.onOptionsItemSelected(item);
}
//点击跳转
public void showPage(int position){
viewPager.setCurrentItem(position);
drawerLayout.closeDrawer(Gravity.START);
}
@Override
protected int getLayoutResId() {
return R.layout.activity_main;
}
}
3.主页面布局 包括DrawerLayout+TabLayout+ViewPager+FrameLayout侧拉的占位布局
<?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:layout_width="match_parent"
android:id="@+id/drawer_layout"
android:layout_height="match_parent"
tools:context=".ui.activity.MainActivity">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<android.support.design.widget.TabLayout
android:id="@+id/bottom_indicator"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
app:tabIndicatorHeight="1dp"
app:tabSelectedTextColor="@color/colorAccent"
app:tabTextColor="@color/colorPrimary"
app:tabIndicatorColor="@android:color/transparent"
/>
<android.support.v4.view.ViewPager
android:id="@+id/contenes"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_above="@id/bottom_indicator"
/>
</RelativeLayout>
<FrameLayout
android:id="@+id/left_deawer"
android:layout_width="200dp"
android:layout_height="match_parent"
android:layout_gravity="start"
/>
</android.support.v4.widget.DrawerLayout>
4.侧拉页面需要的fragment的布局
<?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/left_list"
android:layout_width="0dp"
android:layout_height="0dp"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
android:background="@android:color/white"
/>
</android.support.constraint.ConstraintLayout>
5.侧拉页面需要的多条目布局
5.1侧拉头像布局
<?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"
android:padding="10dp"
xmlns:app="http://schemas.android.com/apk/res-auto">
<ImageView
android:id="@+id/left_image"
android:layout_width="100dp"
android:layout_height="100dp"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
android:src="@mipmap/ic_launcher"
/>
</android.support.constraint.ConstraintLayout>
5.2.侧拉文字布局
<?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/left_text"
android:layout_width="0dp"
android:layout_height="wrap_content"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintBottom_toBottomOf="parent"
android:textSize="20dp"
android:text="text"
android:gravity="center"
android:padding="15dp"
/>
</android.support.constraint.ConstraintLayout>
6.侧拉页面的fragment代码页面 包括点击侧拉的头像进行二次采样换头像
package com.example.zonghelianxi02.ui.fragment;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.net.Uri;
import android.provider.MediaStore;
import android.support.v4.content.CursorLoader;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import com.example.zonghelianxi02.R;
import com.example.zonghelianxi02.ui.activity.MainActivity;
import com.example.zonghelianxi02.ui.adaper.MenusAdaper;
import com.example.zonghelianxi02.util.BitmapUtil;
import java.util.ArrayList;
import java.util.List;
import static android.app.Activity.RESULT_OK;
public class LeftFragment extends BaseFragment {
private ListView listView;
private MenusAdaper adaper;
private final int REQUESTCOAD_NUM = 100;
private Uri uri;
@Override
protected void initData() {
List<String> list = new ArrayList<>();
list.add("首页");
list.add("电影");
list.add("消息");
list.add("图片");
adaper.setmDatas(list);
}
@Override
protected void initView(View view) {
//获取资源id
listView = view.findViewById(R.id.left_list);
//创建适配器
adaper = new MenusAdaper(getActivity());
listView.setAdapter(adaper);
//点击进行图片采样换头像
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, REQUESTCOAD_NUM);
}else{
((MainActivity)getActivity()).showPage(position-1);
}
}
});
}
@Override
protected int getLayoutResId() {
return R.layout.left_fragment;
}
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.moveToFirst();
return cursor.getString(columnIndexOrThrow);
}
private void progressImaage(String s) {
int size = getResources().getDimensionPixelSize(R.dimen.leftIconSize);
BitmapUtil.getInstance().selectBitmap(s, size, size, new BitmapUtil.CallBack() {
@Override
public void onBitmap(Bitmap bitmap) {
adaper.setIconBitmap(bitmap);
}
});
}
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == REQUESTCOAD_NUM && resultCode == RESULT_OK) {
uri = data.getData();
progressImaage(url2Path(uri));
return;
}
}
}
7.侧拉页面的适配器
package com.example.zonghelianxi02.ui.adaper;
import android.content.ComponentName;
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;
import com.example.zonghelianxi02.R;
import java.util.ArrayList;
import java.util.List;
public class MenusAdaper extends BaseAdapter {
private List<String> mDatas;
private Context mContext;
private Bitmap iconBitmap;
public MenusAdaper(Context mContext) {
this.mContext = mContext;
//初始化
mDatas = new ArrayList<>();
}
public void setmDatas(List<String> datas){
mDatas.clear();
if(datas!=null){
mDatas.addAll(datas);
}
notifyDataSetChanged();
}
public void setIconBitmap(Bitmap bitmap){
this.iconBitmap = bitmap;
notifyDataSetChanged();
}
@Override
public int getCount() {
return mDatas.size()+1;
}
@Override
public String getItem(int position) {
//减一是因为第一个条目是图片
//文本条目下标从一开始
return mDatas.get(position-1);
}
@Override
public long getItemId(int position) {
return position;
}
private final int ITEM_COUNT=2;
@Override
public int getViewTypeCount() {
return ITEM_COUNT;
}
private final int IMAGE_TYPE = 0;
private final int TEXT_ITEM = 1;
@Override
public int getItemViewType(int position) {
if(position==0){
return IMAGE_TYPE;
}else{
return TEXT_ITEM;
}
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
if(convertView == null){
convertView = LayoutInflater.from(mContext).inflate(
getItemViewType(position)==IMAGE_TYPE? R.layout.left_item_image:R.layout.left_item_text
,parent,false);
holder = new ViewHolder(convertView);
}else{
holder = (ViewHolder) convertView.getTag();
}
if(getItemViewType(position)==IMAGE_TYPE){
if (iconBitmap!=null){
holder.bindIcon(iconBitmap);
}
}else{
holder.bindText(getItem(position));
}
return convertView;
}
class ViewHolder{
ImageView image;
TextView text;
//获取资源id
public ViewHolder(View convertView) {
image = convertView.findViewById(R.id.left_image);
text = convertView.findViewById(R.id.left_text);
convertView.setTag(this);
}
//绑定图片
public void bindIcon(Bitmap iconBitmap) {
image.setImageBitmap(iconBitmap);
}
//绑定文本
public void bindText(String item) {
text.setText(item);
}
}
}
8.主页面底部导航的适配器
package com.example.zonghelianxi02.ui.adaper;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import com.example.zonghelianxi02.ui.fragment.HomeFragment;
import com.example.zonghelianxi02.ui.fragment.MessageFragment;
import com.example.zonghelianxi02.ui.fragment.MoveFragment;
import com.example.zonghelianxi02.ui.fragment.PickFragment;
public class MainAdaper extends FragmentPagerAdapter {
private String[] pageName = new String[]{
"首页","电影","消息","图片"
};
public MainAdaper(FragmentManager fm) {
super(fm);
}
@Override
public Fragment getItem(int i) {
switch (i){
case 0:
return new HomeFragment();
case 1:
return new MoveFragment();
case 2:
return new MessageFragment();
case 3:
return new PickFragment();
default:
return new Fragment();
}
}
@Override
public int getCount() {
return pageName.length;
}
@Nullable
@Override
public CharSequence getPageTitle(int position) {
return pageName[position];
}
}
轮播图多条目
代码
1.布局页面
<?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">
<com.handmark.pulltorefresh.library.PullToRefreshListView
android:id="@+id/home_pull"
android:layout_width="0dp"
android:layout_height="0dp"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintBottom_toBottomOf="parent"
/>
</android.support.constraint.ConstraintLayout>
2.多条目布局页面
2.1.多条目轮播图布局页
<?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">
<android.support.v4.view.ViewPager
android:id="@+id/home_page"
android:layout_width="0dp"
android:layout_height="240dp"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintBottom_toBottomOf="parent"
/>
<LinearLayout
android:id="@+id/dot"
android:layout_width="wrap_content"
android:layout_height="0dp"
android:orientation="horizontal"
app:layout_constraintRight_toRightOf="@id/home_page"
app:layout_constraintBottom_toBottomOf="@id/home_page"
android:padding="8dp"
/>
<TextView
android:id="@+id/desc"
android:layout_width="0dp"
android:layout_height="wrap_content"
app:layout_constraintLeft_toLeftOf="@id/home_page"
app:layout_constraintBottom_toBottomOf="@id/home_page"
app:layout_constraintRight_toLeftOf="@id/dot"
android:maxLines="1"
android:ellipsize="end"
/>
</android.support.constraint.ConstraintLayout>
2.2.多条目文本页
<?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"
android:padding="10dp"
xmlns:app="http://schemas.android.com/apk/res-auto">
<ImageView
android:id="@+id/home_image"
android:layout_width="120dp"
android:layout_height="150dp"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintBottom_toBottomOf="parent"
/>
<TextView
android:id="@+id/home_title"
android:layout_width="0dp"
android:layout_height="wrap_content"
app:layout_constraintTop_toTopOf="@id/home_image"
app:layout_constraintLeft_toRightOf="@id/home_image"
app:layout_constraintRight_toRightOf="parent"
android:text="title"
android:textSize="20dp"
android:maxLines="2"
/>
<TextView
android:id="@+id/home_ctime"
android:layout_width="0dp"
android:layout_height="wrap_content"
app:layout_constraintBottom_toBottomOf="@id/home_image"
app:layout_constraintLeft_toRightOf="@id/home_image"
app:layout_constraintRight_toRightOf="parent"
android:text="ctime"
android:textSize="20dp"
android:maxLines="2"
/>
</android.support.constraint.ConstraintLayout>
3.逻辑代码也
package com.example.zonghelianxi02.ui.fragment;
import android.view.View;
import android.widget.ListView;
import android.widget.Toast;
import com.example.zonghelianxi02.R;
import com.example.zonghelianxi02.model.HomeBean;
import com.example.zonghelianxi02.ui.adaper.HomeAdaper;
import com.example.zonghelianxi02.util.NetUtil;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshListView;
public class HomeFragment extends BaseFragment {
private PullToRefreshListView refreshListView;
private HomeAdaper adaper;
private String url ="http://api.tianapi.com/military/?key=605fa0a929c8d8b116424df0510c6b2a&num=10";
private int mPage = 1;
@Override
protected void initData() {
if(mPage==1){
loadBunner();
loadData();
}else{
loadData();
}
}
//加载bunner
private void loadBunner() {
NetUtil.getIntance().getRequest(url, HomeBean.class, new NetUtil.CallBack<HomeBean>() {
@Override
public void onSuccess(HomeBean o) {
if(o==null || !o.isSuccess()){
Toast.makeText(getActivity(),"请求错误",Toast.LENGTH_SHORT).show();
return;
}
adaper.setmBunner(o.getNewslist());
}
});
}
//加载新闻
private void loadData() {
NetUtil.getIntance().getRequest(url, HomeBean.class, new NetUtil.CallBack<HomeBean>() {
@Override
public void onSuccess(HomeBean o) {
if(o==null||!o.isSuccess()){
Toast.makeText(getActivity(),"请求错误",Toast.LENGTH_SHORT).show();
refreshListView.onRefreshComplete();
return;
}
if(mPage==1){
adaper.setmData(o.getNewslist());
}else{
adaper.addmData(o.getNewslist());
}
mPage++;
//停止刷新和加载
refreshListView.onRefreshComplete();
}
});
}
@Override
protected void initView(View view) {
//获取资源id
refreshListView = view.findViewById(R.id.home_pull);
//创建适配器
adaper = new HomeAdaper(getActivity());
refreshListView.setAdapter(adaper);
//设置支持刷新和加载
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();
}
});
}
@Override
protected int getLayoutResId() {
return R.layout.home_fragment;
}
}
4.适配器也面
package com.example.zonghelianxi02.ui.adaper;
import android.annotation.SuppressLint;
import android.content.Context;
import android.os.Handler;
import android.os.Message;
import android.support.v4.view.ViewPager;
import android.util.TypedValue;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import com.example.zonghelianxi02.R;
import com.example.zonghelianxi02.model.HomeBean;
import com.nostra13.universalimageloader.core.ImageLoader;
import java.util.ArrayList;
import java.util.List;
public class HomeAdaper extends BaseAdapter {
private List<HomeBean.NewslistBean> mData;
private List<HomeBean.NewslistBean> mBunner;
private Context mContext;
public HomeAdaper(Context mContext) {
this.mContext = mContext;
//初始化
mData = new ArrayList<>();
mBunner = new ArrayList<>();
}
//判断是否有Bunner
public boolean hasBunner(){
return mBunner.size()>0;
}
//刷新bunner
public void setmBunner(List<HomeBean.NewslistBean> bunner){
mBunner.clear();
if(bunner!=null){
mBunner.addAll(bunner);
}
notifyDataSetChanged();
}
//刷新新闻
public void setmData(List<HomeBean.NewslistBean> datas){
mData.clear();
if(datas!=null){
mData.addAll(datas);
}
notifyDataSetChanged();
}
//追加新闻
public void addmData(List<HomeBean.NewslistBean> datas){
if(datas!=null){
mData.addAll(datas);
}
notifyDataSetChanged();
}
@Override
public int getCount() {
return hasBunner()?mData.size()+1:mData.size();
}
@Override
public HomeBean.NewslistBean getItem(int position) {
return mData.get(hasBunner()?position-1:position);
}
@Override
public long getItemId(int position) {
return position;
}
private final int ITEM_COUNT = 2;
@Override
public int getViewTypeCount() {
return ITEM_COUNT;
}
private final int BUNNER_TYPE = 0;
private final int TEXT_TYPE = 1;
@Override
public int getItemViewType(int position) {
return position==0&&hasBunner()?BUNNER_TYPE:TEXT_TYPE;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
if(getItemViewType(position)==BUNNER_TYPE){
BunnerViewHolder viewHolder;
if(convertView == null){
convertView = LayoutInflater.from(mContext).inflate(R.layout.home_bunner_item,parent,false);
viewHolder = new BunnerViewHolder(convertView);
}else{
viewHolder = (BunnerViewHolder) convertView.getTag();
}
viewHolder.bindBunner(mBunner);
}else{
DataViewHolder viewHolder;
if(convertView == null){
convertView = LayoutInflater.from(mContext).inflate(R.layout.home_text_item,parent,false);
viewHolder = new DataViewHolder(convertView);
}else{
viewHolder = (DataViewHolder) convertView.getTag();
}
viewHolder.bindData(getItem(position));
}
return convertView;
}
//图片条目的寄存器
class BunnerViewHolder{
ViewPager viewPager;
LinearLayout dot;
TextView desc;
//获取资源id
public BunnerViewHolder(View convertView) {
viewPager = convertView.findViewById(R.id.home_page);
dot = convertView.findViewById(R.id.dot);
desc = convertView.findViewById(R.id.desc);
convertView.setTag(this);
}
//设置值
public void bindBunner(final List<HomeBean.NewslistBean> mBunner) {
//创建适配器
BunnerAdaper adaper = new BunnerAdaper(mBunner,mContext);
//设置适配器
viewPager.setAdapter(adaper);
//滑动监听
viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
private int index = -1;
@Override
public void onPageScrolled(int i, float v, int i1) {
}
@Override
public void onPageSelected(int i) {
//改变text文本
desc.setText(mBunner.get(i%mBunner.size()).getTitle());
//改变当前点
dot.getChildAt(i%dot.getChildCount()).setSelected(true);
//还原原来点
if(index>=0){
dot.getChildAt(index%dot.getChildCount()).setSelected(false);
}
index = i;
}
@Override
public void onPageScrollStateChanged(int i) {
}
});
//初始化小圆点
initDot(mBunner.size());
//设置中间位置
int center = adaper.getCount()/2;
center = center - center%mBunner.size();
viewPager.setCurrentItem(center);
startLooper();
}
//创建handler
@SuppressLint("HandlerLeak")
private Handler handler = new Handler(){
@Override
public void handleMessage(Message msg) {
viewPager.setCurrentItem(viewPager.getCurrentItem()+1);
handler.sendEmptyMessageDelayed(0,2000);
}
};
//开始轮播
private void startLooper() {
handler.removeCallbacksAndMessages(null);
handler.sendEmptyMessageDelayed(0,2000);
}
//初始化小圆点
private void initDot(int size) {
dot.removeAllViews();
for (int i = 0; i <size ; i++) {
ImageView imageView = new ImageView(mContext);
imageView.setBackgroundResource(R.drawable.select_dot);
//布局参数
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT,
ViewGroup.LayoutParams.WRAP_CONTENT);
int marage = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP,5,
mContext.getResources().getDisplayMetrics());
params.leftMargin = marage;
params.rightMargin = marage;
dot.addView(imageView,params);
}
}
}
//内容条目寄存器
class DataViewHolder{
ImageView image;
TextView title;
TextView ctime;
//获取资源id
public DataViewHolder(View convertView) {
image = convertView.findViewById(R.id.home_image);
title = convertView.findViewById(R.id.home_title);
ctime = convertView.findViewById(R.id.home_ctime);
convertView.setTag(this);
}
//设置值
public void bindData(HomeBean.NewslistBean item) {
title.setText(item.getTitle());
ctime.setText(item.getCtime());
ImageLoader.getInstance().displayImage(item.getPicUrl(),image);
}
}
}
5.轮播图适配器
package com.example.zonghelianxi02.ui.adaper;
import android.content.Context;
import android.support.annotation.NonNull;
import android.support.v4.view.PagerAdapter;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import com.example.zonghelianxi02.model.HomeBean;
import com.nostra13.universalimageloader.core.ImageLoader;
import java.util.ArrayList;
import java.util.List;
public class BunnerAdaper extends PagerAdapter {
private List<HomeBean.NewslistBean> mBunner;
private Context mContext;
public BunnerAdaper(List<HomeBean.NewslistBean> mBunner, Context mContext) {
this.mBunner = mBunner;
this.mContext = mContext;
}
@Override
public int getCount() {
return mBunner.size()>0?5000:0;
}
@Override
public boolean isViewFromObject(@NonNull View view, @NonNull Object o) {
return view==o;
}
public HomeBean.NewslistBean getItem(int position){
return mBunner.get(position%mBunner.size());
}
@NonNull
@Override
public Object instantiateItem(@NonNull ViewGroup container, int position) {
ImageView imageView = new ImageView(mContext);
imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
container.addView(imageView);
ImageLoader.getInstance().displayImage(getItem(position).getPicUrl(),imageView);
return imageView;
}
@Override
public void destroyItem(@NonNull ViewGroup container, int position, @NonNull Object object) {
container.removeView((View) object);
}
}
fragment嵌套fragment展示数据
代码
1.外部fragment的布局
<?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">
<android.support.design.widget.TabLayout
android:id="@+id/move_layout"
android:layout_width="0dp"
android:layout_height="wrap_content"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent"
/>
<android.support.v4.view.ViewPager
android:id="@+id/move_pager"
android:layout_width="0dp"
android:layout_height="0dp"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toBottomOf="@id/move_layout"
app:layout_constraintBottom_toBottomOf="parent"
/>
</android.support.constraint.ConstraintLayout>
2.内部fragment展示tablayout的适配器 展示头部内容
package com.example.zonghelianxi02.ui.adaper;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import com.example.zonghelianxi02.ui.fragment.MoveListFragment;
public class MovePageAdaper extends FragmentPagerAdapter {
private String[] names = new String[]{
"正在上映","即将上映"
};
private String[] url = new String[]{
"http://172.17.8.100/movieApi/movie/v1/findHotMovieList?count=%d&page=%d",
"http://172.17.8.100/movieApi/movie/v1/findReleaseMovieList?count=%d&page=%d"
};
public MovePageAdaper(FragmentManager fm) {
super(fm);
}
@Override
public Fragment getItem(int i) {
switch (i){
default:
Bundle bundle = new Bundle();
bundle.putString("url",url[i]);
MoveListFragment moveListFragment = new MoveListFragment();
moveListFragment.setArguments(bundle);
return moveListFragment;
}
}
@Nullable
@Override
public CharSequence getPageTitle(int position) {
return names[position];
}
@Override
public int getCount() {
return names.length;
}
}
3.外部fragment逻辑代码也
package com.example.zonghelianxi02.ui.fragment;
import android.support.design.widget.TabLayout;
import android.support.v4.view.ViewPager;
import android.view.View;
import com.example.zonghelianxi02.R;
import com.example.zonghelianxi02.ui.adaper.MovePageAdaper;
public class MoveFragment extends BaseFragment {
private TabLayout tabLayout;
private ViewPager viewPager;
@Override
protected void initData() {
}
@Override
protected void initView(View view) {
//获取资源id
tabLayout = view.findViewById(R.id.move_layout);
viewPager = view.findViewById(R.id.move_pager);
viewPager.setAdapter(new MovePageAdaper(getChildFragmentManager()));
tabLayout.setupWithViewPager(viewPager);
}
@Override
protected int getLayoutResId() {
return R.layout.move_fragment;
}
}
4.内部展示展示内容的fragment布局
<?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">
<com.handmark.pulltorefresh.library.PullToRefreshListView
android:id="@+id/pull_list"
android:layout_width="0dp"
android:layout_height="0dp"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintBottom_toBottomOf="parent"
/>
</android.support.constraint.ConstraintLayout>
5.展示内容条目的布局
<?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"
android:padding="10dp"
xmlns:app="http://schemas.android.com/apk/res-auto">
<ImageView
android:id="@+id/move_image"
android:layout_width="120dp"
android:layout_height="150dp"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintBottom_toBottomOf="parent"
/>
<TextView
android:id="@+id/name"
android:layout_width="0dp"
android:layout_height="wrap_content"
app:layout_constraintTop_toTopOf="@id/move_image"
app:layout_constraintLeft_toRightOf="@id/move_image"
app:layout_constraintRight_toRightOf="parent"
android:maxLines="3"
android:textSize="20sp"
android:text="name"
/>
<TextView
android:id="@+id/summary"
android:layout_width="0dp"
android:layout_height="wrap_content"
app:layout_constraintLeft_toRightOf="@id/move_image"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintBottom_toBottomOf="@id/move_image"
android:maxLines="3"
android:textSize="20sp"
android:text="summary"
/>
</android.support.constraint.ConstraintLayout>
6.展示内用的适配器
package com.example.zonghelianxi02.ui.adaper;
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.example.zonghelianxi02.R;
import com.example.zonghelianxi02.model.MoveBean;
import com.nostra13.universalimageloader.core.ImageLoader;
import java.util.ArrayList;
import java.util.List;
public class MoveListAdaper extends BaseAdapter {
private List<MoveBean.ResultBean> mData;
private Context mContext;
public MoveListAdaper(Context mContext) {
this.mContext = mContext;
//初始化
mData = new ArrayList<>();
}
public void setmData(List<MoveBean.ResultBean> result){
mData.clear();
if(result!=null){
mData.addAll(result);
}
notifyDataSetChanged();
}
public void addmResult(List<MoveBean.ResultBean> result){
if(result!=null){
mData.addAll(result);
}
notifyDataSetChanged();
}
//删除
public void setDelete(int position){
mData.remove(position-1);
notifyDataSetChanged();
}
@Override
public int getCount() {
return mData.size();
}
@Override
public MoveBean.ResultBean getItem(int position) {
return mData.get(position);
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
if(convertView == null){
convertView = LayoutInflater.from(mContext).inflate(R.layout.move_item,parent,false);
holder = new ViewHolder(convertView);
}else{
holder = (ViewHolder) convertView.getTag();
}
holder.bind(getItem(position));
return convertView;
}
class ViewHolder{
ImageView image;
TextView name;
TextView summary;
View convertView;
public ViewHolder(View convertView) {
image = convertView.findViewById(R.id.move_image);
name = convertView.findViewById(R.id.name);
summary = convertView.findViewById(R.id.summary);
convertView.setTag(this);
}
public void bind(MoveBean.ResultBean item) {
name.setText(item.getName());
summary.setText(item.getSummary());
ImageLoader.getInstance().displayImage(item.getImageUrl(),image);
}
}
}
7.内容的fragment页面 逻辑代码页面
package com.example.zonghelianxi02.ui.fragment;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.Toast;
import com.example.zonghelianxi02.R;
import com.example.zonghelianxi02.db.MoveDao;
import com.example.zonghelianxi02.model.MoveBean;
import com.example.zonghelianxi02.ui.adaper.MoveListAdaper;
import com.example.zonghelianxi02.util.NetUtil;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshListView;
public class MoveListFragment extends BaseFragment {
private PullToRefreshListView refreshListView;
private int mPage = 1;
private String url;
private MoveListAdaper moveListAdaper;
private final int LOAD_COUNT = 10;
//加载数据
@Override
protected void initData() {
NetUtil.getIntance().getRequest(String.format(url,LOAD_COUNT, mPage), MoveBean.class, new NetUtil.CallBack<MoveBean>() {
@Override
public void onSuccess(MoveBean o) {
if(o==null || !o.isSuccess()){
Toast.makeText(getActivity(),"请求失败",Toast.LENGTH_SHORT).show();
//停止刷新
refreshListView.onRefreshComplete();
return;
}
//数据库操作
if(mPage == 1){
MoveDao.getIntance(getActivity()).deleteAll(url.hashCode());
}
MoveDao.getIntance(getActivity()).addAll(url.hashCode(),o.getResult());
//刷新适配器
if(mPage == 1){
//从数据库查询
moveListAdaper.setmData(MoveDao.getIntance(getActivity()).select(url.hashCode()));
//通过解析出来传到适配器直接展示
//moveListAdaper.setmData(o.getResult());
}else{
//从数据库查询
moveListAdaper.addmResult(MoveDao.getIntance(getActivity()).select(url.hashCode()));
//通过解析出来传到适配器直接展示
// moveListAdaper.addmResult(o.getResult());
}
//页面自增
mPage++;
//停止刷新/加载
refreshListView.onRefreshComplete();
if(o.getResult().size()<LOAD_COUNT){
refreshListView.setMode(PullToRefreshBase.Mode.PULL_FROM_START);
}else{
refreshListView.setMode(PullToRefreshBase.Mode.BOTH);
}
}
});
}
//初始化view
@Override
protected void initView(View view) {
//通过fragment把url地址接口传回来
url = getArguments().getString("url");
//获取资源id
refreshListView = view.findViewById(R.id.pull_list);
//创建适配器
moveListAdaper = new MoveListAdaper(getActivity());
//设置适配器
refreshListView.setAdapter(moveListAdaper);
//设置支持刷新和加载
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();
}
});
//点击删除
refreshListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
//删除数据库
MoveDao.getIntance(getActivity()).delete(url.hashCode(),moveListAdaper.getItem(position).getId());
//删除页面
moveListAdaper.setDelete(position);
}
});
}
@Override
protected int getLayoutResId() {
return R.layout.move_list_fragment;
}
}
8.数据库创建表的 页面
package com.example.zonghelianxi02.db;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
public class SqlitHelper extends SQLiteOpenHelper {
public SqlitHelper(Context context) {
super(context, "Move.db", null, 1);
}
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("create table moves(_id integer primary key autoincrement," +
"id integer," +
"name text," +
"summary text," +
"url text," +
"type integer)");
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
}
9.数据库写增删改查方法页面
package com.example.zonghelianxi02.db;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import com.example.zonghelianxi02.model.MoveBean;
import java.util.ArrayList;
import java.util.List;
public class MoveDao {
private static MoveDao intance;
private final SqlitHelper helper;
private final SQLiteDatabase sb;
public MoveDao(Context context) {
//创建数据库
helper = new SqlitHelper(context);
sb = helper.getWritableDatabase();
}
public static MoveDao getIntance(Context context) {
if (intance == null) {
intance = new MoveDao(context);
}
return intance;
}
//添加
public void add(int type, MoveBean.ResultBean bean) {
ContentValues values = new ContentValues();
values.put("id", bean.getId());
values.put("name", bean.getName());
values.put("summary", bean.getSummary());
values.put("url", bean.getImageUrl());
values.put("type", type);
sb.insert("moves", null, values);
}
public void addAll(int type, List<MoveBean.ResultBean> datas) {
try {
sb.beginTransaction();
for (MoveBean.ResultBean bean : datas) {
add(type, bean);
}
sb.setTransactionSuccessful();
} finally {
sb.endTransaction();
}
}
//删除
public void delete(int type, int id) {
sb.delete("moves", "id=? and type=?", new String[]{String.valueOf(id), String.valueOf(type)});
}
public void deleteAll(int type) {
sb.delete("moves", "type=?", new String[]{String.valueOf(type)});
}
//查询
public List<MoveBean.ResultBean> select(int type) {
List<MoveBean.ResultBean> list = new ArrayList<>();
Cursor moves = sb.query("moves", null, "type=?", new String[]{String.valueOf(type)}, null, null, null);
if (moves != null) {
while (moves.moveToNext()) {
String id1 = moves.getString(moves.getColumnIndex("id"));
Integer id = Integer.valueOf(id1);
String url = moves.getString(moves.getColumnIndex("url"));
String name = moves.getString(moves.getColumnIndex("name"));
String summary = moves.getString(moves.getColumnIndex("summary"));
MoveBean.ResultBean bean = new MoveBean.ResultBean(id,url,name,summary);
list.add(bean);
}
moves.close();
}
return list;
}
}
PullToRefreshGridView展示图片页面
代码
1.布局页面
<?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">
<com.handmark.pulltorefresh.library.PullToRefreshGridView
android:id="@+id/pick_pull"
android:layout_width="0dp"
android:layout_height="0dp"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent"
android:numColumns="auto_fit"
/>
</android.support.constraint.ConstraintLayout>
2.内容条目布局页
<?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/pick_image"
android:layout_width="200dp"
android:layout_height="200dp"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintBottom_toBottomOf="parent"
/>
</android.support.constraint.ConstraintLayout>
3.内容适配器页
package com.example.zonghelianxi02.ui.adaper;
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.example.zonghelianxi02.R;
import com.example.zonghelianxi02.model.PickBean;
import com.nostra13.universalimageloader.core.ImageLoader;
import java.util.ArrayList;
import java.util.List;
public class PickAdaper extends BaseAdapter {
private List<PickBean.NewslistBean> mData;
private Context mContext;
public PickAdaper(Context mContext) {
this.mContext = mContext;
//初始化
mData = new ArrayList<>();
}
//刷新
public void setmData(List<PickBean.NewslistBean> datas){
mData.clear();
if(datas!=null){
mData.addAll(datas);
}
notifyDataSetChanged();
}
//加载
public void addmData(List<PickBean.NewslistBean> datas){
if(datas!=null){
mData.addAll(datas);
}
notifyDataSetChanged();
}
@Override
public int getCount() {
return mData.size();
}
@Override
public PickBean.NewslistBean getItem(int position) {
return mData.get(position);
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
if(convertView == null){
convertView = LayoutInflater.from(mContext).inflate(R.layout.pick_item,parent,false);
holder = new ViewHolder(convertView);
}else{
holder = (ViewHolder) convertView.getTag();
}
holder.bind(getItem(position));
return convertView;
}
//创建寄存器
class ViewHolder{
ImageView image;
TextView text;
public ViewHolder(View convertView) {
image = convertView.findViewById(R.id.pick_image);
convertView.setTag(this);
}
public void bind(PickBean.NewslistBean item) {
ImageLoader.getInstance().displayImage(item.getPicUrl(),image);
}
}
}
4.内容逻辑代码也
package com.example.zonghelianxi02.ui.fragment;
import android.view.View;
import android.widget.GridView;
import android.widget.Toast;
import com.example.zonghelianxi02.R;
import com.example.zonghelianxi02.model.PickBean;
import com.example.zonghelianxi02.ui.adaper.PickAdaper;
import com.example.zonghelianxi02.util.NetUtil;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshGridView;
public class PickFragment extends BaseFragment {
private PullToRefreshGridView gridView;
private PickAdaper adaper;
private String url = "http://api.tianapi.com/meinv/?key=605fa0a929c8d8b116424df0510c6b2a&num=10";
private int mPage = 1;
private final int LOAD_NUM = 10;
@Override
protected void initData() {
NetUtil.getIntance().getRequest(url, PickBean.class, new NetUtil.CallBack<PickBean>() {
@Override
public void onSuccess(PickBean o) {
if(o==null || !o.isSussecc()){
Toast.makeText(getActivity(),"请求错误",Toast.LENGTH_SHORT).show();
gridView.onRefreshComplete();
return;
}
if(mPage == 1){
adaper.setmData(o.getNewslist());
}else{
adaper.addmData(o.getNewslist());
}
mPage++;
gridView.onRefreshComplete();
if(o.getNewslist().size()<LOAD_NUM){
gridView.setMode(PullToRefreshBase.Mode.PULL_FROM_START);
}
}
});
}
@Override
protected void initView(View view) {
//获取资源id
gridView = view.findViewById(R.id.pick_pull);
//创建适配器
adaper = new PickAdaper(getActivity());
gridView.setAdapter(adaper);
//设置支持刷新加载
gridView.setMode(PullToRefreshBase.Mode.BOTH);
//设置监听
gridView.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener2<GridView>() {
@Override
public void onPullDownToRefresh(PullToRefreshBase<GridView> refreshView) {
mPage=1;
initData();
}
@Override
public void onPullUpToRefresh(PullToRefreshBase<GridView> refreshView) {
initData();
}
});
}
@Override
protected int getLayoutResId() {
return R.layout.pick_fragment;
}
}
通用
1.Application初始化图片
package com.example.zonghelianxi02.Application;
import android.app.Application;
import android.graphics.Bitmap;
import com.example.zonghelianxi02.R;
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() {
super.onCreate();
ImageLoader.getInstance().init(new ImageLoaderConfiguration.Builder(this)
.diskCacheSize(50*1024*1024)
.memoryCacheSizePercentage(10)
.defaultDisplayImageOptions(new DisplayImageOptions.Builder()
.bitmapConfig(Bitmap.Config.RGB_565)
.cacheInMemory(true)
.cacheOnDisk(true)
.showImageOnFail(R.mipmap.ic_launcher)
.showImageForEmptyUri(R.mipmap.ic_launcher)
.showImageOnLoading(R.mipmap.ic_launcher)
.build())
.build());
}
}
2.工具类
package com.example.zonghelianxi02.util;
import android.annotation.SuppressLint;
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;
import java.net.URLConnection;
public class NetUtil {
private static NetUtil intance;
private Gson gson;
public NetUtil() {
gson = new Gson();
}
public static NetUtil getIntance() {
if(intance==null){
intance = new NetUtil();
}
return intance;
}
//执行网络请求返回String
public String getRequest(String urlStr){
String result = "";
try {
//定义url地址
URL url = new URL(urlStr);
//打开连接
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
//设置请求方式
urlConnection.setRequestMethod("GET");
//设置超时
urlConnection.setReadTimeout(5000);
urlConnection.setConnectTimeout(5000);
//获取请求码
int responseCode = urlConnection.getResponseCode();
if(responseCode==200){
result = stream2String(urlConnection.getInputStream());
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return result;
}
//将字节流转换为字符流
private String stream2String(InputStream inputStream) throws IOException {
StringBuilder builder = new StringBuilder();
BufferedReader br = new BufferedReader(new InputStreamReader(inputStream));
for (String tmp = br.readLine();tmp!=null;tmp=br.readLine()){
builder.append(tmp);
}
return builder.toString();
}
//执行网络请求返回bean
public <E> E getRequest(String urlStr,Class clazz){
return (E) gson.fromJson(getRequest(urlStr),clazz);
}
//定义接口
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);
}
}
3.二次采样工具类
package com.example.zonghelianxi02.util;
import android.annotation.SuppressLint;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
public class BitmapUtil {
private static BitmapUtil instance;
public BitmapUtil() {
}
public static BitmapUtil getInstance() {
if(instance==null){
instance = new BitmapUtil();
}
return instance;
}
//二次采样请求
public Bitmap selectBitmap(String imagePath,int width,int height){
//第一次只加载宽高信息
BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeFile(imagePath,options);
//根据原始宽高和请求宽高计算采样lv
options.inSampleSize = Math.max(options.outWidth/width,options.outHeight/height);
//设置真正加载图片
options.inJustDecodeBounds = false;
return BitmapFactory.decodeFile(imagePath,options);
}
//定义接口
public interface CallBack{
void onBitmap(Bitmap bitmap);
}
//回调请求
@SuppressLint("StaticFieldLeak")
public void selectBitmap(String imagePath, final int width, final int height, final CallBack callBack){
new AsyncTask<String,Void,Bitmap>(){
@Override
protected Bitmap doInBackground(String... strings) {
return selectBitmap(strings[0],width,height);
}
@Override
protected void onPostExecute(Bitmap bitmap) {
callBack.onBitmap(bitmap);
}
}.execute(imagePath);
}
}
4.二次采样在values里建一个dimens.xml
<?xml version="1.0" encoding="utf-8"?>
<resources>
<dimen name="leftIconSize">100dp</dimen>
</resources>
5.轮播图小圆点
5.1默认圆点
<?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="#909090"
/>
</shape>
5.2选中圆点
<?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="#900000"
/>
</shape>
5.3select
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:drawable="@drawable/shape_sel_dot" android:state_selected="true"/>
<item android:drawable="@drawable/shape_normal_dot"/>
</selector>
用到的bean类
1首页bean
package com.example.zonghelianxi02.model;
import java.util.List;
public class HomeBean {
private int code;
private String msg;
private List<NewslistBean> newslist;
private final int SUCCESS_CODE=200;
public boolean isSuccess(){
return SUCCESS_CODE == code;
}
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 {
private String ctime;
private String title;
private String description;
private String picUrl;
private String url;
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;
}
}
}
2.电影bean
package com.example.zonghelianxi02.model;
import java.util.List;
public class MoveBean {
private String message;
private String status;
private List<ResultBean> result;
private final String SUCCESS_STATUS = "0000";
public boolean isSuccess(){
return SUCCESS_STATUS.equals(status);
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public List<ResultBean> getResult() {
return result;
}
public void setResult(List<ResultBean> result) {
this.result = result;
}
public static class ResultBean {
private boolean followMovie;
private int id;
private String imageUrl;
private String name;
private int rank;
private String summary;
public ResultBean(int id, String imageUrl, String name, String summary) {
this.id = id;
this.imageUrl = imageUrl;
this.name = name;
this.summary = summary;
}
public boolean isFollowMovie() {
return followMovie;
}
public void setFollowMovie(boolean followMovie) {
this.followMovie = followMovie;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getImageUrl() {
return imageUrl;
}
public void setImageUrl(String imageUrl) {
this.imageUrl = imageUrl;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getRank() {
return rank;
}
public void setRank(int rank) {
this.rank = rank;
}
public String getSummary() {
return summary;
}
public void setSummary(String summary) {
this.summary = summary;
}
}
}
3.图片bean
package com.example.zonghelianxi02.model;
import java.util.List;
public class PickBean {
private int code;
private String msg;
private List<NewslistBean> newslist;
private final int SUCCESS_CODE =200;
public boolean isSussecc(){
return SUCCESS_CODE==code;
}
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 {
private String ctime;
private String title;
private String description;
private String picUrl;
private String url;
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;
}
}
}
用到的依赖
implementation 'com.android.support:design:28.0.0'
implementation project(':library')
implementation 'com.google.code.gson:gson:2.8.5'
implementation 'com.nostra13.universalimageloader:universal-image-loader:1.9.5'