侧滑的多条目展示头像的二次采样电影的加载,数据库的缓存

XML的侧拉的布局

<?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"
    android:layout_height="match_parent"
    tools:context=".ui.MainActivity">

<RelativeLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent" >

    <android.support.design.widget.TabLayout
        android:id="@+id/tabLayout"
        android:layout_width="match_parent"
        android:layout_height="60dp"
        app:tabGravity="fill"
        android:layout_alignParentBottom="true"
        ></android.support.design.widget.TabLayout>

    <android.support.v4.view.ViewPager
        android:id="@+id/viewpager"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_above="@id/tabLayout"
        ></android.support.v4.view.ViewPager>
</RelativeLayout>

<FrameLayout
    android:id="@+id/leftlayout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_gravity="start"
    ></FrameLayout>

</android.support.v4.widget.DrawerLayout>

MainActivity中侧拉的加载

super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

    viewPager=findViewById(R.id.viewpager);
    tabLayout=findViewById(R.id.tabLayout);

    if(savedInstanceState==null){
        getSupportFragmentManager().beginTransaction()
                .add(R.id.leftlayout,new LeftFragment())
                .commit();
    }

    getSupportActionBar().setDisplayHomeAsUpEnabled(true);
    drawerLayout=findViewById(R.id.drawer);
    toggle = new ActionBarDrawerToggle(this, drawerLayout, R.string.open, R.string.close);
    drawerLayout.addDrawerListener(toggle);
    toggle.syncState();

    viewPager.setAdapter(new MyMainPager(getSupportFragmentManager()));
    tabLayout.setupWithViewPager(viewPager);

}

public void showPage(int position) {
    viewPager.setCurrentItem(position);
    drawerLayout.closeDrawer(Gravity.START);
}

public  boolean onOptionsItemSelected(MenuItem item){
    if(toggle.onOptionsItemSelected(item)){
        return true;
    }
    return super.onOptionsItemSelected(item);
}

首页的tablayout

private String[] names=new String[]{
            "首页","推荐","我的"
    };

public MyMainPager(FragmentManager fm) {
    super(fm);
}

@Override
public Fragment getItem(int i) {
    switch (i){
        case 0:
            return new OneFragment();
        case 1:
            return new TuiFragment();
        case 2:
            return new MineFragment();
    }
    return null;
}

@Override
public int getCount() {
    return names.length;
}

@Nullable
@Override
public CharSequence getPageTitle(int position) {
    return names[position];
}

侧拉的Fragment和头像的二次采样

private ListView listView;
    private MyLeftAdapter 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) {
    super.onViewCreated(view, savedInstanceState);

    listView=view.findViewById(R.id.left_listview);
    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,100);
            }
            ((MainActivity)getActivity()).showPage(position-1);
        }
    });

    adapter = new MyLeftAdapter(getActivity());
    listView.setAdapter(adapter);
}



@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    if(requestCode==100&&resultCode==getActivity().RESULT_OK){
        Uri uri = data.getData();
        progressImage(url2Path(uri));
        return;
    }
}
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 progressImage(String imagePath) {
    int size = getResources().getDimensionPixelSize(R.dimen.leftIconSize);
    Bitmap bitmap = BitmapUtil.scaleBitmap(imagePath, size, size);
    adapter.setIconBitmap(bitmap);
}

二次采样的Util

public static Bitmap scaleBitmap(String imagePath,int width,int height){
        //第一次加载宽高信息
        BitmapFactory.Options options = new BitmapFactory.Options();
        options.inJustDecodeBounds=true;
        BitmapFactory.decodeFile(imagePath,options);
        //根据图片原始宽高 和请求宽高 计算采样率
        options.inSampleSize=Math.max(options.outWidth/width,options.outWidth/height);
        //设置真正加载图片
        options.inJustDecodeBounds=false;
        //第二次加载图片
        return BitmapFactory.decodeFile(imagePath,options);
    }

侧拉的布局

<ListView
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/left_listview"
    android:background="#ccc"
    android:layout_width="200dp"
    android:layout_height="match_parent">
</ListView>

侧拉的Adapter的多条目

private String[] data=new String[]{
            "首页","推荐","我的"
    };
    private Context context;

private Bitmap iconBitmap;

public MyLeftAdapter(Context context) {
    this.context = context;
}
public void setIconBitmap(Bitmap bitmap) {
    this.iconBitmap=bitmap;
    notifyDataSetChanged();
}

@Override
public int getCount() {
    return data.length+1;
}

@Override
public int getItemViewType(int position) {
    return position==0?0:1;
}

@Override
public int getViewTypeCount() {
    return 2;
}

@Override
public String getItem(int position) {
    if(position==0) {
        return null;
    }
    return data[position-1];
}

@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(
                getItemViewType(position) == 0 ? R.layout.item_icon_menu : R.layout.item_text_menu
                , parent, false);
        viewHolder = new ViewHolder(convertView);
    } else {
        viewHolder = (ViewHolder) convertView.getTag();
    }

    if (getItemViewType(position) == 0) {
        //绑定icon
        if(iconBitmap != null) {
            viewHolder.bindIcon(iconBitmap);
        }
    } else {
        viewHolder.bindData(getItem(position));
    }
    //别返回空
    return convertView;
}



class ViewHolder {
    TextView menuTitle;
    ImageView icon;

    public ViewHolder(View itemView) {
        menuTitle = itemView.findViewById(R.id.text);
        icon = itemView.findViewById(R.id.icon);
        //绑定
        itemView.setTag(this);
    }

    public void bindIcon(Bitmap bitmap) {
        icon.setImageBitmap(bitmap);
    }

    public void bindData(String title) {
        menuTitle.setText(title);
    }
}

TwoFragment的布局

<android.support.design.widget.TabLayout
        android:id="@+id/tabLayout1"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        app:tabMaxWidth="0dp"
        app:tabMode="fixed"
        app:tabGravity="fill"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        ></android.support.design.widget.TabLayout>

<android.support.v4.view.ViewPager
    android:id="@+id/viewPager1"
    android:layout_width="match_parent"
    android:layout_height="0dp"
    app:layout_constraintTop_toBottomOf="@id/tabLayout1"
    app:layout_constraintLeft_toLeftOf="parent"
    app:layout_constraintRight_toRightOf="parent"
    app:layout_constraintBottom_toBottomOf="parent"
    ></android.support.v4.view.ViewPager>

TwoFragment的Fragment

private ViewPager viewPager;
    private TabLayout tabLayout;

@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
    return inflater.inflate(R.layout.fargmentone,container,false);
}

@Override
public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
    super.onViewCreated(view, savedInstanceState);

    viewPager=view.findViewById(R.id.viewPager1);
    tabLayout=view.findViewById(R.id.tabLayout1);

    viewPager.setAdapter(new MyChilerAdapter(getChildFragmentManager()));
    tabLayout.setupWithViewPager(viewPager);
}

第二个布局里的tablayout的正在热播和即将上映的Fragment和数据库

private PullToRefreshListView contents;
    private String url;
    private MyListAdapter adapter;
    private int mpage=1;
    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        return inflater.inflate(R.layout.activity_doing,container,false);
    }

@Override
public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
    super.onViewCreated(view, savedInstanceState);

    contents=view.findViewById(R.id.contents);

    url = getArguments().getString("url");
    adapter = new MyListAdapter(getActivity());
    contents.setAdapter(adapter);

    contents.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener2<ListView>() {
        @Override
        public void onPullDownToRefresh(PullToRefreshBase<ListView> refreshView) {
            mpage=1;
            loadData();
        }

        @Override
        public void onPullUpToRefresh(PullToRefreshBase<ListView> refreshView) {
            loadData();
        }
    });
    loadData();

}

private void loadData() {

    Util.getInstance().getRequset(url + mpage, MoveResponse.class, new Util.Callback<MoveResponse>() {
        @Override
        public void onSuccess(MoveResponse o){
            if(o==null||!o.isSuccess()){
                Toast.makeText(getActivity(),"请求错误",Toast.LENGTH_SHORT).show();
            }
            if(mpage==1){
                UserDao.getInstance(getActivity()).delAll(url.hashCode());
            }

            UserDao.getInstance(getActivity()).addAll(url.hashCode(),o.getResult());
            if(mpage==1){
                adapter.setDatas(o.getResult());
            }else{
                adapter.addDatas(o.getResult());
            }

            mpage++;
            contents.onRefreshComplete();
            if(o.getResult().size()<10){
                contents.setMode(PullToRefreshBase.Mode.PULL_FROM_START);
            }else{
                contents.setMode(PullToRefreshBase.Mode.BOTH);
            }
        }
    });

}

获取正在上映和即将上映数据的Adapter

private List<MoveResponse.ResultBean> datas;
    private Context context;

public MyListAdapter(Context context) {
    this.context = context;
    datas=new ArrayList<>();
}

public void setDatas(List<MoveResponse.ResultBean> mdatas) {
   // this.datas = datas;
    datas.clear();
    if(mdatas!=null){
        datas.addAll(mdatas);
    }
    notifyDataSetChanged();
}
public void addDatas(List<MoveResponse.ResultBean> mdatas) {
    // this.datas = datas;
    if(mdatas!=null){
        datas.addAll(mdatas);
    }
    notifyDataSetChanged();
}

@Override
public int getCount() {
    return datas.size();
}

@Override
public MoveResponse.ResultBean getItem(int position) {
    return datas.get(position);
}

@Override
public long getItemId(int position) {
    return position;
}

@Override
public View getView(int position, View convertView, ViewGroup parent) {
    ViewHolder vh;
    if(convertView==null){
        convertView=LayoutInflater.from(context).inflate(R.layout.activity_item,parent,false);
        vh=new ViewHolder(convertView);
    }else{
        vh= (ViewHolder) convertView.getTag();
    }
    vh.bindData(getItem(position));
    return convertView;
}
class ViewHolder{
    ImageView icon;
    TextView title;
    TextView summary;

    public ViewHolder(View view){
        title=view.findViewById(R.id.title);
        icon=view.findViewById(R.id.icon1);
        summary=view.findViewById(R.id.summary);
        view.setTag(this);
    }
    public void bindData(MoveResponse.ResultBean item) {
        title.setText(item.getName());
        summary.setText(item.getSummary());
        ImageLoader.getInstance().displayImage(item.getImageUrl(),icon);
    }
}

正在上映和即将上映的Adapter

private String[] mdata=new String[]{
            "正在热映","即将上映"
    };
    private String[] urls=new String[]{
            "http://172.17.8.100/movieApi/movie/v1/findHotMovieList?count=10&page=",
            "http://172.17.8.100/movieApi/movie/v1/findReleaseMovieList?count=10&page="
    };


public MyChilerAdapter(FragmentManager fm) {
    super(fm);
}

@Override
public Fragment getItem(int i) {
    switch (i){
        default:
            Bundle bundle=new Bundle();
            bundle.putString("url",urls[i]);
            DoingFragment oneFragment = new DoingFragment();
            oneFragment.setArguments(bundle);
            return oneFragment;
    }
}

@Override
public int getCount() {
    return mdata.length;
}

@Nullable
@Override
public CharSequence getPageTitle(int position) {
    return mdata[position];
}

}

数据库的创建

public Sqlite( Context context) {
        super(context, "User.db", null, 1);
    }


@Override
public void onCreate(SQLiteDatabase db) {
    db.execSQL("create table users(id integer primary key autoincrement," +
            "_id text," +
            "url text," +
            "name text," +
            "summary text," +
            "type integer)");
}

@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {

}

Dao层的创建

public class UserDao {
    private SQLiteDatabase database;
    private static UserDao instance;

private UserDao(Context context){
    database=new Sqlite(context).getReadableDatabase();
}

public static UserDao getInstance(Context context) {
    if(instance==null){
        instance=new UserDao(context);
    }
    return instance;
}

public void add(int type, MoveResponse.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);
    database.insert("users",null,values);
}

public void addAll(int type, List<MoveResponse.ResultBean> datas){
    try {
        database.beginTransaction();
        for (MoveResponse.ResultBean bean : datas) {
            add(type, bean);
        }
        database.setTransactionSuccessful();
    }finally {
        database.endTransaction();
    }

}

public void del(int type,String id){
    database.delete("users","id=?and type=?",new String[]{id,String.valueOf(type)});
}
public void delAll(int type){
    database.delete("users","type=?",new String[]{String.valueOf(type)});
}

public List<MoveResponse.ResultBean> query(int type){
    ArrayList<MoveResponse.ResultBean> result = new ArrayList<>();
    Cursor cursor = database.query("users", null, "type=?", new String[]{String.valueOf(type)},null,null,null);
    if(cursor != null) {
        while (cursor.moveToNext()) {
            result.add(
                    new MoveResponse.ResultBean(
                            cursor.getString(cursor.getColumnIndex("id")),
                            cursor.getString(cursor.getColumnIndex("url")),
                            cursor.getString(cursor.getColumnIndex("name")),
                            cursor.getString(cursor.getColumnIndex("summary"))
                    )
            );
        }
        cursor.close();
    }

    return result;
}

第二个布局里的tablayout的正在热播和即将上映的Xml

<com.handmark.pulltorefresh.library.PullToRefreshListView
        android:id="@+id/contents"
        android:layout_width="0dp"
        android:layout_height="0dp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

Util工具类和判断是否联网

public boolean IsIntent(Context context){
        ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo info = cm.getActiveNetworkInfo();

    return info.isAvailable()&&info!=null;
}

private static Util instance;
public Util(){

}

public static Util getInstance() {
    if(instance==null){
        instance=new Util();
    }
    return instance;
}

public interface Callback<T>{
    void onSuccess(T t);
}

public void getRequset(String dataUrl, final Class clazz, final Callback callback){
    new AsyncTask<String,Void,Object>(){
        @Override
        protected Object doInBackground(String... strings) {
            return getRequset(strings[0],clazz);
        }

        @Override
        protected void onPostExecute(Object o) {
            callback.onSuccess(o);
        }
    }.execute(dataUrl);
}

private <T> T getRequset(String dataUrl,Class clazz){
    return (T) new Gson().fromJson(getRequset(dataUrl),clazz);
}

private String getRequset(String dataUrl){
    String result="";
    try {
        URL url=new URL(dataUrl);
        HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
        urlConnection.setReadTimeout(3000);
        urlConnection.setConnectTimeout(3000);
        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 {
    StringBuffer stringBuffer = new StringBuffer();
    BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
    for (String tmp=bufferedReader.readLine();tmp!=null;tmp=bufferedReader.readLine()){
        stringBuffer.append(tmp);
    }
    return stringBuffer.toString();
}

App图片的全局配置

ImageLoader.getInstance().init(
                new ImageLoaderConfiguration.Builder(this)
                .defaultDisplayImageOptions(
                        new DisplayImageOptions.Builder()
                                .cacheInMemory(true)
                                .cacheOnDisk(true)
                                .displayer(new RoundedBitmapDisplayer(9))
                                .bitmapConfig(Bitmap.Config.RGB_565)
                                .build()
                ).build()
        );

获取数据的item的布局

<ImageView
        android:id="@+id/icon1"
        android:layout_width="100dp"
        android:layout_height="130dp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

<TextView
    android:id="@+id/title"
    android:layout_width="0dp"
    android:layout_marginTop="30dp"
    android:layout_height="wrap_content"
    app:layout_constraintLeft_toRightOf="@id/icon1"
    app:layout_constraintRight_toRightOf="parent"
    app:layout_constraintTop_toTopOf="@id/icon1" />

<TextView
    android:id="@+id/summary"
    android:layout_width="0dp"
    android:layout_marginTop="20dp"
    android:layout_height="wrap_content"
    android:maxLines="3"
    app:layout_constraintTop_toBottomOf="@id/title"
    app:layout_constraintLeft_toRightOf="@id/icon1"
    app:layout_constraintRight_toRightOf="parent" />

侧滑的布局

<ListView
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/left_listview"
    android:background="#ccc"
    android:layout_width="200dp"
    android:layout_height="match_parent">

</ListView>

<TextView
        android:id="@+id/text"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:gravity="center"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"/>

<ImageView
        android:id="@+id/icon"
        android:layout_width="100dp"
        android:layout_height="100dp"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        android:background="@mipmap/ic_launcher"
        />

在这里插

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值