TabLayout + ViewPager輪播圖 (雙層巢狀),側拉展示條目(頭像加listview,點選頭像可切換)PullToRefreshListView重新整理載入
阿新 • • 發佈:2018-12-22
模組簡介:
1.底部:TabLayout + ViewPager輪播圖
2.主頁面可測拉 展示頭像,可選擇系統相簿,切換圖片(二級取樣)
3.TabLayout + ViewPager巢狀TabLayout + ViewPager以展示
正在上映 和 ***即將上映***條目
4.資料庫操作(Dao層增刪查)
主頁面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:layout_height="match_parent" android:id="@+id/draw" android:orientation="vertical" tools:context=".MainActivity"> <RelativeLayout android:layout_width="match_parent" android:layout_height="match_parent" > <!--匯入design包--> <android.support.design.widget.TabLayout android:id="@+id/main_tablayout" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_alignParentBottom="true" app:tabGravity="fill" app:tabSelectedTextColor="@color/colorPrimary" app:tabIndicatorHeight="3dp" ></android.support.design.widget.TabLayout> <android.support.v4.view.ViewPager android:id="@+id/main_viewpager" android:layout_width="match_parent" android:layout_height="match_parent" android:layout_above="@+id/main_tablayout" ></android.support.v4.view.ViewPager> </RelativeLayout> <!--側滑頁面 動態新增Fragment --> <FrameLayout android:id="@+id/leftframelayout" android:layout_width="300dp" android:layout_gravity="start" android:layout_height="match_parent"></FrameLayout> </android.support.v4.widget.DrawerLayout>
側滑佈局
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:background="#ccff" android:orientation="vertical" > <ImageView android:id="@+id/lf_image" android:layout_width="150dp" android:layout_height="150dp" android:background="@drawable/ic_launcher_background" /> <ListView android:id="@+id/lf_listview" android:layout_width="wrap_content" android:layout_height="wrap_content"></ListView> </LinearLayout>
側滑listview介面卡
package jx.com.adapter; import android.content.Context; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.TextView; import java.util.List; import jx.com.week3_1.R; public class LeftFragmentAdapter extends BaseAdapter { private List<String> list; private Context context; public LeftFragmentAdapter(List<String> list, Context context) { this.list = list; this.context = context; } @Override public int getCount() { return list.size(); } @Override public Object getItem(int position) { return list.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(context).inflate(R.layout.leftitem,parent,false); holder = new ViewHolder(); holder.text = convertView.findViewById(R.id.left_item); convertView.setTag(holder); }else { holder = (ViewHolder) convertView.getTag(); } holder.text.setText(list.get(position)); return convertView; } class ViewHolder{ TextView text; } }
MainActivity,側滑fragment點選操作
public class MainActivity extends AppCompatActivity {
private DrawerLayout drawerLayout;
private ViewPager viewPager;
private TabLayout tabLayout;
private FrameLayout frameLayout;
private ActionBar actionBar;
private ActionBarDrawerToggle toggle;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initView();
initData(savedInstanceState);
}
private void initData(Bundle savedInstanceState) {
actionBar = getSupportActionBar();
actionBar .setDisplayHomeAsUpEnabled(true);
toggle = new ActionBarDrawerToggle(this,drawerLayout,R.string.open,R.string.close);
toggle.syncState();
drawerLayout.addDrawerListener(toggle);
if(savedInstanceState==null){
getSupportFragmentManager().beginTransaction()
.add(R.id.leftframelayout,new LeftFragment())
.commit();
}
viewPager.setAdapter(new TabAdapter(getSupportFragmentManager()));
tabLayout.setupWithViewPager(viewPager);
}
public void getcurr(int position){
viewPager.setCurrentItem(position);
drawerLayout.closeDrawers();
}
private void initView() {
drawerLayout = findViewById(R.id.draw);
viewPager = findViewById(R.id.main_viewpager);
tabLayout = findViewById(R.id.main_tablayout);
frameLayout = findViewById(R.id.leftframelayout);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
if(toggle.onOptionsItemSelected(item)){
return true;
}
return super.onOptionsItemSelected(item);
}
}
TabLayout + viewPager介面卡
package jx.com.fragment;
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 TabAdapter extends FragmentPagerAdapter {
String[] str = new String[]{"首頁","視訊","我的"};
public TabAdapter(FragmentManager fm) {
super(fm);
}
@Override
public Fragment getItem(int position) {
switch (position){
case 0:
return new ShouyeFragment();
case 1:
return new ShipinFragment();
case 2:
return new WodeFragment();
default:
return new Fragment();
}
}
@Nullable
@Override
public CharSequence getPageTitle(int position) {
return str[position];
}
@Override
public int getCount() {
return str.length;
}
}
圖片二級取樣工具類
package jx.com.netutil;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
public class NetUtil {
public static NetUtil instance;
public static NetUtil getInstance(){
if(instance==null){
instance = new NetUtil();
}
return instance;
}
public Bitmap getBitmap(String imagefile,int width,int height){
BitmapFactory.Options opts = new BitmapFactory.Options();
opts.inJustDecodeBounds = true;
BitmapFactory.decodeFile(imagefile,opts);
opts.inSampleSize = Math.max(opts.outHeight/height,opts.outWidth/width);
opts.inJustDecodeBounds = false;
return BitmapFactory.decodeFile(imagefile,opts);
}
/*//tup質量壓縮: 只改變檔案大小,基本不改變記憶體佔用
public static Bitmap compress(Bitmap bitmap, int qual, File output) {
Bitmap result = bitmap;
try {
//縮放後的
//bitmap.compress(Bitmap.CompressFormat.JPEG, 100, new FileOutputStream(new File(Environment.getExternalStorageDirectory(), "tmp.jpg")));
//壓縮後的,儲存到output檔案
bitmap.compress(Bitmap.CompressFormat.JPEG, qual, new FileOutputStream(output));
//再次解析壓縮後的圖片
result = BitmapFactory.decodeFile(output.getAbsolutePath());
} catch (FileNotFoundException e) {
e.printStackTrace();
};
return result;
}*/
}
網路獲取資料工具類(json解析 介面回撥)
package jx.com.week3_1;
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 {
public static NetUtil instance;
public static NetUtil getInstance(){
if (instance == null){
instance = new NetUtil();
}
return instance;
}
public interface CallBack<T>{
void getmessage(T t);
}
public void getload(String myuri, final Class clazz, final CallBack callBack){
new AsyncTask<String, Void, Object>() {
@Override
protected Object doInBackground(String... strings) {
return getload(strings[0],clazz);
}
@Override
protected void onPostExecute(Object o) {
super.onPostExecute(o);
callBack.getmessage(o);
}
}.execute(myuri);
}
public <E> E getload(String myuri,Class clazz){
E e = (E) new Gson().fromJson(getload(myuri), clazz);
return e;
}
public String getload(String myuri){
String stream = "";
try {
URL url = new URL(myuri);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setReadTimeout(5000);
connection.setConnectTimeout(5000);
int responseCode = connection.getResponseCode();
if(responseCode == 200){
stream = stream(connection.getInputStream());
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return stream;
}
public String stream(InputStream is) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(is));
StringBuilder builder = new StringBuilder();
for (String tmp = br.readLine();tmp!=null;tmp = br.readLine()){
builder.append(tmp);
}
return builder.toString();
}
}
巢狀的TabLayout+ViewPager(正在上映和即將上映)
<?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:background="#ccc">
<android.support.design.widget.TabLayout
android:id="@+id/sp_tablayout"
android:layout_width="0dp"
android:layout_height="wrap_content"
app:tabMode="fixed"
app:tabGravity="fill"
app:tabMaxWidth="0dp"
app:tabIndicatorHeight="3dp"
app:tabSelectedTextColor="@color/colorPrimary"
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/sp_viewpager"
android:layout_width="0dp"
android:layout_height="0dp"
app:layout_constraintTop_toBottomOf="@+id/sp_tablayout"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintBottom_toBottomOf="parent"
></android.support.v4.view.ViewPager>
</android.support.constraint.ConstraintLayout>
巢狀的tabLayout + viewpager展示資料頁
private TabLayout tabLayout;
private ViewPager viewPager;
@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.shipin,container,false);
tabLayout = view.findViewById(R.id.sp_tablayout);
viewPager = view.findViewById(R.id.sp_viewpager);
return view;
}
@Override
public void onActivityCreated(@Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
viewPager.setAdapter(new MoveAdapter(getChildFragmentManager()));
tabLayout.setupWithViewPager(viewPager);
}
}
展示正在上映和即將上映的介面卡(用同一個Fragment加Adapter)
public class MoveAdapter extends FragmentPagerAdapter {
private String[] str = new String[]{"正在上映","即將上映"};
private String[] myurl = 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 MoveAdapter(FragmentManager fm) {
super(fm);
}
@Override
public Fragment getItem(int position) {
switch (position){
default:
Bundle bundle =new Bundle();
bundle.putString("url",myurl[position]);
zhengzaiFragment zhengzai= new zhengzaiFragment();
zhengzai.setArguments(bundle);
return zhengzai;
}
}
@Nullable
@Override
public CharSequence getPageTitle(int position) {
return str[position];
}
@Override
public int getCount() {
return str.length;
}
}
展示正在上映和即將上映Fragment+ PullToRefreshListView重新整理載入
private PullToRefreshListView listView;
private int flag;
private String uri;
private int mpage=1;
private MoveListAdapter adapter;
private final int COUNT = 10;
private NewDao dao;
@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.zhengzai,container,false);
listView = view.findViewById(R.id.zh_listview);
return view;
}
@Override
public void onActivityCreated(@Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
uri = getArguments().getString("url");
dao = new NewDao(getActivity());
flag = 1;
adapter = new MoveListAdapter(getActivity());
listView.setAdapter(adapter);
//支援重新整理載入
listView.setMode(PullToRefreshBase.Mode.BOTH);
listView.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener2<ListView>() {
@Override
public void onPullDownToRefresh(PullToRefreshBase<ListView> refreshView) {
flag = 1;
getinit();
}
@Override
public void onPullUpToRefresh(PullToRefreshBase<ListView> refreshView) {
getinit();
}
});
getinit();
}
private void getinit(){
NetUtil.getInstance().getload(uri + mpage, NewBean.class, new NetUtil.CallBack<NewBean>() {
@Override
public void getmessage(NewBean o) {
if(o==null || !o.isSuccess()){
Toast.makeText(getActivity(),"請求失敗",Toast.LENGTH_SHORT).show();
listView.onRefreshComplete();
return;
}
if(flag == 1){
dao.delete();
}
List<NewBean.Result> result = o.getResult();
dao.add(result);
List<NewBean.Result> select = dao.select();
if(flag == 1){
adapter.setMlist(select);
}else {
adapter.addMlist(select);
}
flag++;
listView.onRefreshComplete();
if (o.getResult().size()<=10){
listView.setMode(PullToRefreshBase.Mode.PULL_FROM_START);
}else {
listView.setMode(PullToRefreshBase.Mode.BOTH);
}
}
});
}
}
子條目佈局
<?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">
<TextView
android:id="@+id/text1"
android:layout_width="0dp"
android:layout_height="wrap_content"
app:layout_constraintTop_toTopOf="parent"
android:layout_marginTop="30dp"
app:layout_constraintLeft_toLeftOf="parent"
android:layout_marginLeft="20dp"
app:layout_constraintRight_toLeftOf="@+id/image"
/>
<TextView
android:id="@+id/text2"
android:layout_width="0dp"
android:layout_height="wrap_content"
app:layout_constraintTop_toBottomOf="@+id/text1"
app:layout_constraintLeft_toLeftOf="parent"
android:layout_marginTop="30dp"
android:maxLines="3"
android:ellipsize="end"
android:layout_marginLeft="20dp"
app:layout_constraintRight_toLeftOf="@+id/image"
/>
<ImageView
android:id="@+id/image"
android:layout_width="150dp"
android:layout_height="150dp"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent"
/>
</android.support.constraint.ConstraintLayout>
ImageLoader 工具類(Application)+儲存
public class Imageloder extends Application {
@Override
public void onCreate() {
super.onCreate();
ImageLoaderConfiguration configuration = null;
try {
configuration = new ImageLoaderConfiguration.Builder(this)
.defaultDisplayImageOptions(new DisplayImageOptions.Builder()
.cacheInMemory(true)
.cacheOnDisk(true)
.build())
.diskCache(new LruDiskCache(new File(Environment.getExternalStorageDirectory(),"image"),new Md5FileNameGenerator(),10*1024*1024))
.build();
} catch (IOException e) {
e.printStackTrace();
}
ImageLoader.getInstance().init(configuration);
}
}
建立資料庫 ++ 建立表
package jx.com.sqlhelper;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.support.annotation.Nullable;
public class MySqliteHelper extends SQLiteOpenHelper {
public MySqliteHelper(@Nullable Context context) {
super(context, "new", null, 1);
}
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("create table news(id integer primary key autoincrement," +
"name text," +
"summary text," +
"imageUrl text)");
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
}
Dao層(增刪查)
package jx.com.dao;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import java.util.ArrayList;
import java.util.List;
import jx.com.bean.NewBean;
import jx.com.sqlhelper.MySqliteHelper;
public class NewDao {
private SQLiteDatabase base;
public NewDao (Context context){
MySqliteHelper mySqliteHelper = new MySqliteHelper(context);
base = mySqliteHelper.getReadableDatabase();
}
public void add(List<NewBean.Result> result){
ContentValues values = new ContentValues();
for (int i = 0;i<result.size();i++){
values.put("name",result.get(i).getName());
values.put("summary",result.get(i).getSummary());
values.put("imageUrl",result.get(i).getImageUrl());
base.insert("news",null,values);
}
}
public List<NewBean.Result> select(){
List<NewBean.Result> list = new ArrayList<>();
Cursor query = base.query("news", null, null, null, null, null, null);
while (query.moveToNext()){
String name = query.getString(query.getColumnIndex("name"));
String summary = query.getString(query.getColumnIndex("summary"));
String imageUrl = query.getString(query.getColumnIndex("imageUrl"));
NewBean.Result bean = new NewBean.Result(name, summary, imageUrl);
list.add(bean);
}
return list;
}
public void delete(){
base.delete("news",null,null);
}
}