RecyclerView 的使用我就不再多说,接下来的几篇文章主要说一下 RecyclerView 的实用小功能,包括 列表宫格的切换,吸顶效果,多布局效果等,今天这篇文章就来实现一下列表宫格的切换,效果如下
数据来源于知乎日报API,采用 okhttp+retrofit 组合方式请求获取,网络请求没有进行二次封装,只是简单请求数据源,对于有需求的用户自行进行封装修改。
//万能适配器
implementation 'com.github.CymChad:BaseRecyclerViewAdapterHelper:2.9.50'
//卡片布局
implementation 'androidx.cardview:cardview:1.0.0'
//图片加载
implementation 'com.github.bumptech.glide:glide:4.9.0'
//json解析
implementation 'com.alibaba:fastjson:1.2.61'
//标题栏
implementation 'com.github.goweii:ActionBarEx:3.2.2'
// 只引入ActionBarEx
implementation 'com.github.goweii.ActionBarEx:actionbarex:3.2.2'
// 引入ActionBarCommon/Search/Super,依赖于ActionBarEx
implementation 'com.github.goweii.ActionBarEx:actionbarex-common:3.2.2'
使用如下 URL 进行数据请求:API 使用的 HTTP Method 均为 GET
https://news-at.zhihu.com/api/3/news/hot
响应实例:
{
"recent": [
{
"news_id": 3748552,
"thumbnail": "http://p3.zhimg.com/67/6a/676a8337efec71a100eea6130482091b.jpg",
"title": "长得漂亮能力出众性格单纯的姑娘为什么会没有男朋友?",
"url": "http://daily.zhihu.com/api/2/news/3748552"
}
]
}
根据实例生成实体类 NewsListBean 实现序列换接口 Serializable
public class NewsListBean implements Serializable {
private String date;
private List recent;
public String getDate() {
return date;
}
public void setDate(String date) {
this.date = date;
}
public List getRecent() {
return recent;
}
public void setRecent(List recent) {
this.recent = recent;
}
public static class Recent implements Serializable {
private String news_id;
private String thumbnail;
private String title;
private String url;
public String getNews_id() {
return news_id;
}
public void setNews_id(String news_id) {
this.news_id = news_id;
}
public String getThumbnail() {
return thumbnail;
}
public void setThumbnail(String thumbnail) {
this.thumbnail = thumbnail;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
}
}
写一个 接口类用来管理 API ,可以单独放在一个文件夹下
public interface ApiUrl {
@GET("/api/4/news/hot")
Call getPic();
}
这里使用了三方库 ActionBarEx 实现了沉浸式标题栏,使用了系统的 ProgressBar 实现请求加载框
列表子布局 ,采用 CardView 卡片布局
public class NewsListAdapter extends BaseQuickAdapter {
public NewsListAdapter(int layoutResId, @Nullable List data) {
super(layoutResId, data);
}
@Override
protected void convert(@NonNull BaseViewHolder helper, NewsListBean.Recent item) {
helper.setText(R.id.news_title, item.getTitle());
String img = item.getThumbnail();
ImageView newsImage = helper.getView(R.id.news_image);
Glide.with(mContext).
asBitmap().
load(img).
diskCacheStrategy(DiskCacheStrategy.ALL).
into(newsImage);
helper.addOnClickListener(R.id.zh_card_View);
}
}
public abstract class BaseActivity extends AppCompatActivity {
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
Window window = getWindow();
// 5.0以上系统状态栏透明
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
window.getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
| View.SYSTEM_UI_FLAG_LAYOUT_STABLE | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
window.setStatusBarColor(Color.TRANSPARENT);
}
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
// 全屏显示,隐藏状态栏和导航栏,拉出状态栏和导航栏显示一会儿后消失。
window.getDecorView().setSystemUiVisibility(
View.SYSTEM_UI_FLAG_LAYOUT_STABLE
// | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
| View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
// | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION
// | View.SYSTEM_UI_FLAG_FULLSCREEN
| View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
} else {
// 全屏显示,隐藏状态栏
window.getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_FULLSCREEN);
}
}
//预防软键盘挡住输入框
getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN);
//禁止横屏
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
super.onCreate(savedInstanceState);
}
}
这里主要通过一个 boolean 值 isGrid 来判断是否切换状态来加载不同的布局,以及布局管理器来达到实际效果
public class MainActivity extends BaseActivity {
private RecyclerView zhLv;
private ProgressBar proBar;
private NewsListAdapter adapter;
private List mList = new ArrayList<>();
private static final int REQUEST_EXTERNAL_STORAGE = 1;
private static String[] PERMISSIONS_STORAGE = {
Manifest.permission.READ_EXTERNAL_STORAGE,
Manifest.permission.WRITE_EXTERNAL_STORAGE};
private ImageView menuBtn;
private LinearLayoutManager layoutManager;
private ImageView btnImg;
private LinearLayout backLayoput;
public static void verifyStoragePermissions(Activity activity) {
int permission = ActivityCompat.checkSelfPermission(activity,
Manifest.permission.WRITE_EXTERNAL_STORAGE);
if (permission != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(activity, PERMISSIONS_STORAGE,
REQUEST_EXTERNAL_STORAGE);
}
}
private boolean isGrid = false;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
verifyStoragePermissions(MainActivity.this);
initView();
initData();
menuBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
switchLayout();
}
});
}
private void switchLayout() {
if (isGrid) {
layoutManager = new LinearLayoutManager(this);
adapter = new NewsListAdapter(R.layout.zh_item_layout, mList);
zhLv.setAdapter(adapter);
} else {
layoutManager = new GridLayoutManager(this, 2);
adapter = new NewsListAdapter(R.layout.zh_grid__item_layout, mList);
zhLv.setAdapter(adapter);
}
zhLv.setLayoutManager(layoutManager);
isGrid = !isGrid;
}
private void initView() {
zhLv = findViewById(R.id.zh_lv);
proBar = findViewById(R.id.progressbar);
menuBtn = findViewById(R.id.btn_main_menu);
btnImg = findViewById(R.id.btn_main_menu);
backLayoput = findViewById(R.id.btn_back_layout);
backLayoput.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
finish();
}
});
layoutManager = new LinearLayoutManager(MainActivity.this);
zhLv.setLayoutManager(layoutManager);
adapter = new NewsListAdapter(R.layout.zh_item_layout, mList);
zhLv.setAdapter(adapter);
}
private void initData() {
proBar.setVisibility(View.VISIBLE);
Retrofit retrofit = new Retrofit.Builder()
.baseUrl("https://news-at.zhihu.com/")
//设置数据解析器
.addConverterFactory(GsonConverterFactory.create())
.build();
ApiUrl apiUrl = retrofit.create(ApiUrl.class);
Call call = apiUrl.getPic();
call.enqueue(new Callback() {
@Override
public void onResponse(Call call, Response response) {
List recent = response.body().getRecent();
if (response.body() != null && recent.size() > 0) {
try {
mList.addAll(recent);
adapter.setNewData(mList);
proBar.setVisibility(View.GONE);
} catch (Exception e) {
String message = e.getMessage();
e.printStackTrace();
}
}
}
@Override
public void onFailure(Call call, Throwable t) {
Log.e("mmm", "errow " + t.getMessage());
}
}
);
}
}
一个小小的很实用的功能就完成了,下一篇文章会接着实现RecyclerView 吸顶效果,后续还会加上列表本地缓存等功能,Demo 在此系列文章完结附上,不妨点赞收藏哦~
青山不改,绿水长流 有缘江湖再见 ~