说在前面,由于各种adapter,xml布局,bean实体类,Activity,也为了让看懂,代码基本都是“简单粗暴直接不好看”,没啥okhttp和util工具类之类的封装,本篇幅可能有点长吧,大佬请放过,哈~
菜鸡一枚,写得不好,有问题的请指教~~
RecyclerView+json+okhttp+glide实现服务分类和热门主题推荐,显示,自定义接口实现RecyclerView 子item的点击事件,点击对应的item 进入对应的服务,热门详情页面。直接用简单的Intent 数据传递新闻详情信息。也可用WebView 加载新闻详情。
一、【Android项目实战 | 从零开始写app(一)】 创建项目
二、【Android项目实战 | 从零开始写app(二)】实现闪屏页,启动app
三、【Android项目实战 | 从零开始写app(三)】实现引导页,进入登录or主页面
四、【Android项目实战 | 从零开始写app(四)】Okhttp+Gson实现服务端登录验证功能
五、【Android项目实战 | 从零开始写app(五)】okhttp+gson实现服务端注册功能
六、【Android项目实战 | 从零开始写app(六)】用TabLayout+ViewPager搭建App 框架主页面底部导航栏
七、【Android项目实战 | 从零开始写app(七)】优化主页导航栏,禁用主页页面滑动切换效果
八、【Android项目实战 | 从零开始写app(八)】实现app首页广告轮播图切换和搜索跳转
九、【Android项目实战 | 从零开始写app(九)】实现主页底部新闻模块数据的解析
十、【Android项目实战 | 从零开始写app(10)】Okhttp+glide+json+ListView实现新闻模块数据的填充显示
十一、【Android项目实战 | 从零开始写app(11)】实现app首页九宫格服务分类点击跳转
十二、【Android项目实战 | 从零开始写app(12)】实现app首页热门推荐
十三、【Android项目实战 | 从零开始写app(13)】实现服务页面数据的解析
十四、【Android项目实战 | 从零开始写app(14)】实现用户中心模块清除token退出登录&信息修改等功能
十五、【Android项目实战 | 从零开始写app(15)】实现发布模块…
在HomeFragment 加入如下代码:
package com.example.myapp.fragment;
import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.EditorInfo;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.viewpager.widget.ViewPager;
import com.bumptech.glide.Glide;
import com.bumptech.glide.load.resource.bitmap.RoundedCorners;
import com.bumptech.glide.request.RequestOptions;
import com.example.myapp.R;
import com.example.myapp.activity.ApponitmentActivity;
import com.example.myapp.activity.BannerWebView;
import com.example.myapp.activity.BusActivity;
import com.example.myapp.activity.CityStateActivity;
import com.example.myapp.activity.LivingPayActivity;
import com.example.myapp.activity.NewSearchActivity;
import com.example.myapp.activity.NewsWebViewActivity;
import com.example.myapp.activity.ParkActivity;
import com.example.myapp.activity.RecommendWebView;
import com.example.myapp.activity.WeiZhangActivity;
import com.example.myapp.adapter.NewTabAdapter;
import com.example.myapp.adapter.RecommendAdapter;
import com.example.myapp.adapter.RecycleServiceAdapter;
import com.example.myapp.bean.BannerBean;
import com.example.myapp.bean.NewsBean;
import com.example.myapp.bean.RecommendBean;
import com.example.myapp.bean.ServiceBean;
import com.example.myapp.utils.APIConfig;
import com.google.android.material.tabs.TabLayout;
import com.google.gson.Gson;
import com.youth.banner.Banner;
import com.youth.banner.adapter.BannerImageAdapter;
import com.youth.banner.holder.BannerImageHolder;
import com.youth.banner.indicator.CircleIndicator;
import com.youth.banner.listener.OnBannerListener;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
/**
* @ProjectName: MyApp
* @Package: com.example.myapp.fragment
* @ClassName: HomeFragment
* @Description:
* @Author: liyingxia
* @CreateDate: 2021/4/13 21:34
*/
public class HomeFragment extends BaseFragment {
private static final String TAG = HomeFragment.class.getSimpleName();
private TextView tv_more,tv_theme,tv_theme_title;
private EditText ed_search;
private Banner banner;
private RecyclerView home_recyclerview,home_recyclerview1;
private RecycleServiceAdapter recycleServiceAdapter;
private List<ServiceBean.RowsBean> rowsBeanList;
private List<RecommendBean.RowsDTO> recommendList;
private RecommendAdapter recommendAdapter;
private NewsBean newsBean;
private NewsAdapter newsAdapter;
private NewTabAdapter newTabAdapter;
private TabLayout tab_layout;
private ListView home_listview;
private ViewPager view_pager;
private OkHttpClient client = new OkHttpClient();
@SuppressLint("HandlerLeak")
private Handler handler = new Handler() {
@Override
public void handleMessage(@NonNull Message msg) {
super.handleMessage(msg);
if (msg.what==0) {
ServiceBean serviceBean = (ServiceBean) msg.obj;
rowsBeanList = serviceBean.getRows();
recycleServiceAdapter= new RecycleServiceAdapter(getActivity(),rowsBeanList);
home_recyclerview.setLayoutManager(new GridLayoutManager(getActivity(),5));
home_recyclerview.setAdapter(recycleServiceAdapter);
recycleServiceAdapter.setItemClickListener(new RecycleServiceAdapter.MyItemClickListener() {
@Override
public void onItemClick(View view, int position) {
String url = APIConfig.BASE_URL+"/"+rowsBeanList.get(position).getLink();
Intent intent = null;
if (position==0){
intent = new Intent(getActivity(), CityStateActivity.class);
} else if (position==1) {
intent = new Intent(getActivity(), BusActivity.class);
} else if (position==2) {
intent = new Intent(getActivity(), ApponitmentActivity.class);
} else if (position==3) {
intent = new Intent(getActivity(), LivingPayActivity.class);
} else if (position==4) {
intent = new Intent(getActivity(), WeiZhangActivity.class);
} else if (position==5) {
intent = new Intent(getActivity(), ParkActivity.class);
}
Bundle bundle = new Bundle();
bundle.putString("title",rowsBeanList.get(position).getServiceName());
bundle.putString("url",url);
intent.putExtras(bundle);
getActivity().startActivity(intent);
}
});
}
if (msg.what==1) {
RecommendBean recommendBean = (RecommendBean) msg.obj;
recommendList = recommendBean.getRows();
recommendAdapter = new RecommendAdapter(getActivity(),recommendList);
home_recyclerview1.setLayoutManager(new GridLayoutManager(getActivity(),2));
home_recyclerview1.setAdapter(recommendAdapter);
recommendAdapter.setOnItemClickListener(new RecommendAdapter.OnItemClickListener() {
@Override
public void onItemClick(int position, List<RecommendBean.RowsDTO> list) {
String url = APIConfig.BASE_URL+"/"+list.get(position).getLink();
Toast.makeText(getContext(),"url详情:"+url,Toast.LENGTH_LONG).show();
Intent intent = new Intent(getActivity(), RecommendWebView.class);
Bundle bundle = new Bundle();
bundle.putString("title",list.get(position).getServiceName());
bundle.putString("url",url);
intent.putExtras(bundle);
getActivity().startActivity(intent);
}
});
}
}
};
@Override
public View initView() {
Log.i(TAG, "首页的视图被初始化了");
View view = View.inflate(getContext(), R.layout.fragment_home, null);
ed_search = view.findViewById(R.id.ed_search);
banner = view.findViewById(R.id.banner);
home_recyclerview = view.findViewById(R.id.home_recyclerview);
home_recyclerview1 = view.findViewById(R.id.home_recyclerview1);
home_listview = view.findViewById(R.id.home_listview);
tab_layout = view.findViewById(R.id.tab_layout);
view_pager = view.findViewById(R.id.view_pager);
tv_more = view.findViewById(R.id.tv_more);
tv_theme = view.findViewById(R.id.tv_theme);
tv_theme_title = view.findViewById(R.id.tv_theme_title);
return view;
}
/**
* 解决ScrollView 导致ListView 只显示一项问题
* @param listView
*/
public static void setListViewHeightBasedOnChildren(ListView listView){
NewsAdapter newsAdapter = (NewsAdapter) listView.getAdapter();
if (newsAdapter==null){
return;
}
int totalHeight=0;
// newsAdapter.getCount() 获取返回数据项的数目
for (int i=0;newsAdapter.getCount()>i;i++){
View listItem = newsAdapter.getView(i,null,listView);
// 计算子项View的宽高
listItem.measure(0,0);
// 统计所有子项的总高度
totalHeight+=listItem.getMeasuredHeight();
}
ViewGroup.LayoutParams params = listView.getLayoutParams();
params.height = totalHeight+(listView.getDividerHeight()*(newsAdapter.getCount()-1));
//getDividerHeight():获取子项间分隔符占用的高度, params.height 得到整个ListView 完整显示需要的高度
listView.setLayoutParams(params);
}
@Override
public void initData() {
super.initData();
initSearch();
initBanner();
getServiceData();
getRecommendData();
initNews();
}
// 顶部搜索框
public void initSearch(){
ed_search.setOnEditorActionListener(new TextView.OnEditorActionListener() {
@Override
public boolean onEditorAction(TextView textView, int i, KeyEvent keyEvent) {
if (i== EditorInfo.IME_ACTION_SEARCH){
String search = ed_search.getText().toString();
Intent intent = new Intent(getActivity(), NewSearchActivity.class);
intent.putExtra("search",search);
startActivity(intent);
/*HomeFragment fragment = new HomeFragment();
Bundle bundle = new Bundle();
bundle.putString("search",search);
fragment.setArguments(bundle);
return fragment;*/
}
return false;
}
});
tv_more.setOnClickListener(new View.OnClickListener() {
@SuppressLint("ResourceType")
@Override
public void onClick(View view) {
Toast.makeText(getActivity(),"查看更多点击底部进入",Toast.LENGTH_LONG).show();
}
});
tv_theme.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
/*Intent intent = new Intent(getActivity(), ServiceActivity.class);
startActivity(intent);*/
Toast.makeText(getActivity(),"更多主题点击全部服务进入",Toast.LENGTH_LONG).show();
}
});
}
// Banner轮播图
public void initBanner(){
//网络加载图片
List<BannerBean.RowsDTO> list = new ArrayList<>();
list.add(new BannerBean.RowsDTO("http://124.93.196.45:10002/profile/home1.png", null));
list.add(new BannerBean.RowsDTO("http://124.93.196.45:10002/profile/home2.png", null));
list.add(new BannerBean.RowsDTO("http://124.93.196.45:10002/profile/home3.png", null));
list.add(new BannerBean.RowsDTO("http://124.93.196.45:10002/profile/home4.png", null));
banner.setAdapter(new BannerImageAdapter<BannerBean.RowsDTO>(list) {
@Override
public void onBindView(BannerImageHolder holder, BannerBean.RowsDTO data, int position, int size) {
//BannerImageHolder 图片加载自己实现
Glide.with(getActivity())
.load(data.getImgUrl())
.apply(RequestOptions.bitmapTransform(new RoundedCorners(30)))
.into(holder.imageView);
}
}).addBannerLifecycleObserver(this)//添加生命周期观察者
.setIndicator(new CircleIndicator(getActivity()))
.setOnBannerListener(new OnBannerListener() {
@Override
public void OnBannerClick(Object o, int position) {
// getIntent(position);
Intent intent = new Intent(getActivity(), BannerWebView.class);
Bundle bundle = new Bundle();
bundle.putString("url",list.get(position).getImgUrl());
intent.putExtras(bundle);
getActivity().startActivity(intent);
}
});
}
// 请求全部服务
private void getServiceData() {
Request request = new Request.Builder()
.url(APIConfig.BASE_URL+"/service/service/list")
.build();
try {
Call call = client.newCall(request);
call.enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
Log.i("onFailure",e.getMessage());
}
@Override
public void onResponse(Call call, Response response) throws IOException {
if (response.isSuccessful()) {
final String result = response.body().string();
getActivity().runOnUiThread(new Runnable() {
@Override
public void run() {
Gson gson = new Gson();
ServiceBean serviceBean = gson.fromJson(result, ServiceBean.class);
Message msg = new Message();
msg.what=0;
msg.obj=serviceBean;
handler.sendMessage(msg);
}
});
}
}
});
} catch (Exception e) {
e.printStackTrace();
}
}
// 主题推荐
public void getRecommendData(){
Request request = new Request.Builder()
.url(APIConfig.BASE_URL+"/service/service/list?pageNum=1&pageSize=10")
.build();
Call call = client.newCall(request);
call.enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
Log.i("onFailure",e.getMessage());
}
@Override
public void onResponse(Call call, Response response) throws IOException {
if (response.isSuccessful()) {
final String recommend = response.body().string();
getActivity().runOnUiThread(new Runnable() {
@Override
public void run() {
Gson gson = new Gson();
RecommendBean recommendBean = gson.fromJson(recommend,RecommendBean.class);
Message msg = new Message();
msg.what=1;
msg.obj=recommendBean;
handler.sendMessage(msg);
}
});
}
}
});
}
// 新闻数据
public void initNews(){
String[] title = {
"时政","电视","旅游","视频","广播","基层"};
List<Fragment> fragmentlist;
fragmentlist = new ArrayList<>();
fragmentlist.add(new NShizhengFragment());
fragmentlist.add(new NTVFragment());
fragmentlist.add(new NTravelFragment());
fragmentlist.add(new NvideoFragment());
fragmentlist.add(new NbrodcastFragment());
fragmentlist.add(new NJicengFragment());
getNewsData();
newTabAdapter = new NewTabAdapter(getChildFragmentManager(),fragmentlist,title);
newsAdapter = new NewsAdapter();
view_pager.setAdapter(newTabAdapter);
tab_layout.setupWithViewPager(view_pager);
}
// 新闻请求
public void getNewsData(){
Request request = new Request.Builder()
.url(APIConfig.BASE_URL+"/press/press/list")
.build();
Call call = client.newCall(request);
call.enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
Log.i("onFailure",e.getMessage());
}
@Override
public void onResponse(Call call, Response response) throws IOException {
if (response.isSuccessful()) {
String result = response.body().string();
Log.i("请求成功",result);
Gson gson = new Gson();
newsBean = gson.fromJson(result, NewsBean.class);
getActivity().runOnUiThread(new Runnable() {
@Override
public void run() {
home_listview.setAdapter(newsAdapter);
setListViewHeightBasedOnChildren(home_listview);
home_listview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
Intent intent = new Intent(getActivity(), NewsWebViewActivity.class);
ImageView new_img = view.findViewById(R.id.new_img);
new_img.setDrawingCacheEnabled(Boolean.TRUE);
intent.putExtra("bitmap",new_img.getDrawingCache());
intent.putExtra("title",newsBean.getRows().get(i).getTitle());
intent.putExtra("time",newsBean.getRows().get(i).getCreateTime());
intent.putExtra("content",newsBean.getRows().get(i).getContent());
/* Bundle bundle = new Bundle();
bundle.putString("img",newsBean.getRows().get(i).getImgUrl());
bundle.putString("title",newsBean.getRows().get(i).getTitle());
bundle.putString("content",newsBean.getRows().get(i).getContent());
bundle.putString("time",newsBean.getRows().get(i).getContent());
intent.putExtras(bundle);*/
getActivity().startActivity(intent);
}
});
}
});
}
}
});
}
// 新闻适配器
public class NewsAdapter extends BaseAdapter {
@Override
public int getCount() {
return newsBean!=null ? newsBean.getRows().size() : 0;
}
@Override
public Object getItem(int i) {
return newsBean.getRows().get(i);
}
@Override
public long getItemId(int i) {
return i;
}
@Override
public View getView(int i, View view, ViewGroup viewGroup) {
ViewHolder holder;
if (view==null) {
view = View.inflate(getContext(), R.layout.news_item,null);
holder = new ViewHolder();
holder.new_title = view.findViewById(R.id.new_title);
holder.new_context = view.findViewById(R.id.new_context);
holder.new_create = view.findViewById(R.id.new_date);
holder.likeNumber = view.findViewById(R.id.likeNumber);
holder.viewsNumber = view.findViewById(R.id.viewsNumber);
holder.new_img = view.findViewById(R.id.new_img);
view.setTag(holder);
} else {
holder = (ViewHolder) view.getTag();
}
holder.likeNumber.setText(newsBean.getRows().get(i).getLikeNumber()+"");
holder.viewsNumber.setText(newsBean.getRows().get(i).getViewsNumber()+"");
holder.new_create.setText(newsBean.getRows().get(i).getCreateTime());
holder.new_context.setText(newsBean.getRows().get(i).getContent());
holder.new_title.setText(newsBean.getRows().get(i).getTitle());
String url = APIConfig.BASE_URL+newsBean.getRows().get(i).getImgUrl();
Glide.with(getActivity()).load(url).into(holder.new_img);
return view;
}
class ViewHolder{
TextView new_title;
TextView new_context;
TextView new_create;
ImageView new_img;
TextView viewsNumber;
TextView likeNumber;
}
}
}
在layout 目录新建下面对应的xml文件
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout android:orientation="vertical"
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#DFDFDF"
xmlns:app="http://schemas.android.com/apk/res-auto">
<!--顶部搜索框-->
<LinearLayout
android:layout_width="match_parent"
android:layout_height="60dp"
android:orientation="vertical"
android:background="#1A5BDD">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="36dp"
android:layout_marginLeft="24dp"
android:layout_marginTop="11dp"
android:layout_marginRight="24dp"
android:background="@drawable/shape_search_box"
android:gravity="center_horizontal"
android:orientation="horizontal">
<ImageView
android:layout_width="22dp"
android:layout_height="22dp"
android:layout_marginLeft="13dp"
android:layout_gravity="center_vertical"
android:src="@drawable/home_search_icon"/>
<EditText
android:layout_marginLeft="4dp"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="@+id/ed_search"
android:singleLine="true"
android:imeOptions="actionSearch"
android:background="@null"
android:hint="搜索你想看的新闻"
android:textColor="#000"
android:textColorHint="#737373"/>
</LinearLayout>
</LinearLayout>
<com.youth.banner.Banner
android:layout_width="match_parent"
android:layout_height="150dp"
android:background="#BBD9F3"
android:id="@+id/banner"/>
<ScrollView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:fillViewport="true">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<!--服务-->
<androidx.recyclerview.widget.RecyclerView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#B5D6F1"
android:layout_margin="10dp"
android:padding="10dp"
android:id="@+id/home_recyclerview"/>
<!--主题推荐-->
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="15dp"
android:layout_marginRight="15dp"
android:layout_marginTop="10dp"
android:background="@drawable/shape_login_form"
android:orientation="vertical">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="10dp"
android:orientation="horizontal">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="主题推荐"
android:gravity="left"
android:id="@+id/tv_theme_title"/>
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="热门主题 >"
android:gravity="right"
android:id="@+id/tv_theme"/>
</LinearLayout>
<androidx.recyclerview.widget.RecyclerView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#FFFFFF"
android:id="@+id/home_recyclerview1"/>
</LinearLayout>
<!--新闻-->
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="15dp"
android:layout_marginRight="15dp"
android:layout_marginTop="10dp"
android:background="@drawable/shape_login_form"
android:orientation="vertical">
<TextView
android:layout_width="match_parent"
android:id="@+id/tv_more"
android:layout_height="wrap_content"
android:gravity="right"
android:text="查看更多 >"/>
<com.google.android.material.tabs.TabLayout
android:layout_width="match_parent"
android:background="@drawable/shape_login_form"
app:tabGravity="fill"
app:tabMode="fixed"
app:tabTextColor="#121212"
app:tabIndicatorColor="#F8C221"
app:tabSelectedTextColor="#FFC107"
android:layout_height="wrap_content"
android:id="@+id/tab_layout"/>
<androidx.viewpager.widget.ViewPager
android:id="@+id/view_pager"
android:layout_width="match_parent"
android:layout_height="0dp"
android:background="@drawable/shape_login_form"
android:layout_weight="1">
</androidx.viewpager.widget.ViewPager>
<ListView
android:layout_width="match_parent"
android:layout_marginTop="15dp"
android:layout_height="wrap_content"
android:id="@+id/home_listview"/>
</LinearLayout>
</LinearLayout>
</ScrollView>
</LinearLayout>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent"
android:orientation="vertical"
android:layout_weight="1"
android:layout_gravity="center"
android:layout_marginTop="20dp"
android:layout_height="wrap_content">
<ImageView
android:background="@drawable/category_shape"
android:layout_width="30dp"
android:layout_height="30dp"
android:layout_gravity="center"
android:id="@+id/service_img"
android:src="@mipmap/ic_launcher"
/>
<TextView
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:id="@+id/service_name"
android:textSize="20sp"
android:textColor="#131313"
android:layout_gravity="center"
android:text="1111"
/>
LinearLayout>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="15dp"
android:orientation="vertical">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="10dp"
android:layout_marginLeft="15dp"
android:layout_marginRight="15dp"
android:background="@drawable/item_shape"
android:orientation="horizontal">
<ImageView
android:id="@+id/new_img"
android:layout_width="100dp"
android:layout_height="100dp"
android:layout_marginRight="4dp"
android:src="@mipmap/ic_launcher" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:weightSum="1"
android:orientation="vertical">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_marginLeft="8dp"
android:layout_weight="0.6"
android:weightSum="1"
android:orientation="horizontal">
<TextView
android:id="@+id/new_title"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="1"
android:textSize="20dp"
android:textColor="#5B4CB1"
android:text="我是titl"
android:gravity="center_vertical"
android:singleLine="true"/>
<TextView
android:id="@+id/new_date"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:textSize="14dp"
android:layout_gravity="right"
android:text="2020-01-01"
android:layout_marginRight="0dp"
android:gravity="center_vertical"
android:singleLine="true"/>
LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_marginLeft="8dp"
android:layout_weight="0.4"
android:weightSum="1"
android:orientation="horizontal">
<TextView
android:id="@+id/new_context"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="1"
android:textSize="14dp"
android:text="我是新闻内容。。。。。"
android:textColor="#5B4CB1"
android:gravity="center_vertical"
android:singleLine="true"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="22"
android:drawableLeft="@mipmap/like"
android:id="@+id/likeNumber"
android:layout_marginRight="6dp" />
<TextView
android:text="333"
android:drawableLeft="@mipmap/browse"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/viewsNumber"/>
LinearLayout>
LinearLayout>
LinearLayout>
LinearLayout>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:padding="10dp"
android:background="#0B7CF4"
android:gravity="center"
android:layout_height="wrap_content">
<ImageView
android:layout_width="100dp"
android:layout_height="100dp"
android:src="@mipmap/ic_launcher"
android:layout_gravity="center"
android:id="@+id/theme_img"/>
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="智慧医疗"
android:gravity="center"
android:textSize="20sp"
android:textColor="#FFFFFF"
android:id="@+id/theme_name"/>
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="智慧巴士智慧巴士智慧巴士"
android:gravity="center"
android:textSize="16sp"
android:textColor="#fff"
android:id="@+id/theme_desc"/>
LinearLayout>
在adapter中新建NewsAdapter
类,继承baseAdapter,并重写几个方法:
package com.example.myapp.adapter;
import android.content.Context;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import androidx.fragment.app.Fragment;
import com.bumptech.glide.Glide;
import com.example.myapp.bean.NewsBean;
import com.example.myapp.R;
import com.example.myapp.utils.APIConfig;
import java.util.List;
/**
* @ProjectName: MyApp4
* @Package: com.example.myapp4.adapter
* @ClassName: NewsAdapter
* @Description:,
* @Author: liyingxia
* @CreateDate: 2021/3/31 9:20
*/
public class NewsAdapter extends BaseAdapter {
private List<NewsBean.RowsBean> newsBean;
private Context context;
private List<Fragment> fragmentList;
public NewsAdapter(List<NewsBean.RowsBean> newsBean,List<Fragment> fragmentList) {
this.newsBean = newsBean;
this.fragmentList = fragmentList;
}
@Override
public int getCount() {
// return newsBean!=null ? newsBean.getRows().size() : 0;
return newsBean.size();
}
@Override
public Object getItem(int i) {
return newsBean.get(i);
}
@Override
public long getItemId(int i) {
return i;
}
@Override
public View getView(int i, View view, ViewGroup viewGroup) {
ViewHolder holder;
if (view==null) {
view = View.inflate(context, R.layout.news_item,null);
holder = new ViewHolder();
holder.new_title = view.findViewById(R.id.new_title);
holder.new_context = view.findViewById(R.id.new_context);
holder.new_create = view.findViewById(R.id.new_date);
holder.likeNumber = view.findViewById(R.id.likeNumber);
holder.viewsNumber = view.findViewById(R.id.viewsNumber);
holder.new_img = view.findViewById(R.id.new_img);
view.setTag(holder);
} else {
holder = (ViewHolder) view.getTag();
}
holder.likeNumber.setText(newsBean.get(i).getLikeNumber());
holder.viewsNumber.setText(newsBean.get(i).getViewsNumber());
holder.new_create.setText(newsBean.get(i).getCreateTime());
holder.new_context.setText(newsBean.get(i).getContent());
holder.new_title.setText(newsBean.get(i).getTitle());
String url = APIConfig.BASE_URL+newsBean.get(i).getImgUrl();
Glide.with(context).load(url).into(holder.new_img);
return view;
}
class ViewHolder{
TextView new_title;
TextView new_context;
TextView new_create;
ImageView new_img;
TextView viewsNumber;
TextView likeNumber;
}
}
这个是新闻分类标题适配器:
package com.example.myapp.adapter;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentPagerAdapter;
import java.util.List;
/**
* @ProjectName: MyApp4
* @Package: com.example.myapp4.adapter
* @ClassName: NewTabAdapter
* @Description:
* @Author: liyingxia
* @CreateDate: 2021/3/30 18:11
*/
public class NewTabAdapter extends FragmentPagerAdapter {
private List<Fragment> fragmentList;
private String[] titles;
public NewTabAdapter(@NonNull FragmentManager fm, List<Fragment> fragmentList, String[] titles) {
super(fm);
this.fragmentList = fragmentList;
this.titles = titles;
}
/**
* 返回当前的fragment
* @param position: 当前页面的位置
* @return
*/
@NonNull
@Override
public Fragment getItem(int position) {
return fragmentList.get(position);
}
/**
* fragment中的个数
*/
@Override
public int getCount() {
return fragmentList.size();
}
/**
* 返回当前的标题
*/
@Nullable
@Override
public CharSequence getPageTitle(int position) {
return titles[position];
}
}
展示评论数据的适配器:
package com.example.myapp.adapter;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import com.bumptech.glide.Glide;
import com.example.myapp.R;
import com.example.myapp.bean.RecommendBean;
import com.example.myapp.utils.APIConfig;
import java.util.List;
/**
* @ProjectName: MyApp4
* @Package: com.example.myapp4.adapter
* @ClassName: RecommendAdapter
* @Description:
* @Author: liyingxia
* @CreateDate: 2021/4/5 15:58
*/
public class RecommendAdapter extends RecyclerView.Adapter<RecommendAdapter.MyViewHolder> {
private List<RecommendBean.RowsDTO> list;
private LayoutInflater layoutInflater;
private Context context;
// 3. 声明接口
private OnItemClickListener mOnItemClickListener;
// 1. 定义接口
public interface OnItemClickListener{
void onItemClick(int position, List<RecommendBean.RowsDTO> list);
}
// 2. 提供set方法给Activity/fragment调用
public void setOnItemClickListener(OnItemClickListener listener){
mOnItemClickListener = listener;
}
public RecommendAdapter(Context context,List<RecommendBean.RowsDTO> list) {
this.list=list;
this.context = context;
this.layoutInflater = LayoutInflater.from(context);
}
@NonNull
@Override
public MyViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
View view = layoutInflater.inflate(R.layout.recommend_item,parent,false);
MyViewHolder myViewHolder = new MyViewHolder(view);
return myViewHolder;
}
@Override
public void onBindViewHolder(@NonNull MyViewHolder holder, int position) {
holder.theme_name.setText(list.get(position).getServiceName());
holder.theme_desc.setText(list.get(position).getServiceDesc());
Glide.with(context).load(APIConfig.BASE_URL+list.get(position).getImgUrl()).into(holder.theme_img);
}
@Override
public int getItemCount() {
return list.size();
}
public class MyViewHolder extends RecyclerView.ViewHolder{
private TextView theme_name;
private TextView theme_desc;
private ImageView theme_img;
public MyViewHolder(@NonNull View view) {
super(view);
this.theme_desc = view.findViewById(R.id.theme_desc);
this.theme_name = view.findViewById(R.id.theme_name);
this.theme_img = view.findViewById(R.id.theme_img);
// 4. 将监听传递给自定义接口
view.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
if (mOnItemClickListener!=null) {
mOnItemClickListener.onItemClick(getAdapterPosition(),list);
}
}
});
}
}
}
显示服务数据的适配器:
package com.example.myapp.adapter;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import com.bumptech.glide.Glide;
import com.example.myapp.R;
import com.example.myapp.bean.ServiceBean;
import com.example.myapp.utils.APIConfig;
import java.util.List;
/**
* @ProjectName: MyApp
* @Package: com.example.myapp.adapter
* @ClassName: RecycleServiceAdapter
* @Description:
* @Author: liyingxia
* @CreateDate: 2021/4/23 10:05
*/
public class RecycleServiceAdapter extends RecyclerView.Adapter<RecycleServiceAdapter.MyViewHolder> {
private LayoutInflater layoutInflater;
private List<ServiceBean.RowsBean> rowsBeans;
private Context context;
private MyItemClickListener mItemClickListener;
/**
* 构造方法 传入参数
* @param context
* @param rowsBeans
*/
public RecycleServiceAdapter(Context context,List<ServiceBean.RowsBean> rowsBeans) {
this.rowsBeans = rowsBeans;
this.context = context;
layoutInflater = LayoutInflater.from(context);
}
@NonNull
@Override
public MyViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
// 创建ViewHolder, 返回每一项的布局
View view = layoutInflater.inflate(R.layout.service_item,parent,false);
MyViewHolder myViewHolder = new MyViewHolder(view,mItemClickListener);
return myViewHolder;
}
// 将数据与控件绑定
@Override
public void onBindViewHolder(@NonNull MyViewHolder holder, int position) {
holder.service_name.setText(rowsBeans.get(position).getServiceName());
String url = APIConfig.BASE_URL + rowsBeans.get(position).getImgUrl();
Glide.with(context).load(url).into(holder.service_img);
}
// 返回Item总条数
@Override
public int getItemCount() {
// return 10;
return rowsBeans.size();
}
// 内部类,绑定控件
public class MyViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
private TextView service_name;
private ImageView service_img;
private MyItemClickListener myListener;
public MyViewHolder(@NonNull View view,MyItemClickListener myItemClickListener) {
super(view);
this.myListener = myItemClickListener;
itemView.setOnClickListener(this);
service_img = view.findViewById(R.id.service_img);
service_name = view.findViewById(R.id.service_name);
}
@Override
public void onClick(View view) {
if (myListener!=null) {
myListener.onItemClick(view,getPosition());
}
}
}
//创建一个回调接口
public interface MyItemClickListener {
void onItemClick(View view,int position);
}
//在activity中adapter中调用此方法,将点击事件监听传递过去,并赋值给全局监听
public void setItemClickListener(MyItemClickListener myItemClickListener){
this.mItemClickListener = myItemClickListener;
}
}
ApponitmentActivity,BusActivity,CityStateActivity,LivingPayActivity,ParkActivity,WeiZhangActivity等基本一致,后面需要填充什么内容自己实现,好吧~
这里只放一个:
package com.example.myapp.activity;
import android.os.Bundle;
import android.view.View;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.TextView;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import com.example.myapp.R;
public class CityStateActivity extends AppCompatActivity {
private Toolbar toolbar;
private WebView webView;
private String title;
private TextView service_name;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_city_state);
toolbar = (Toolbar) findViewById(R.id.toolbar);
webView = (WebView) findViewById(R.id.webView);
service_name = findViewById(R.id.service_name);
initData();
}
private void initData() {
toolbar.setNavigationIcon(R.mipmap.top_bar_left_back);
toolbar.setNavigationOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
finish();
}
});
Bundle bundle = new Bundle();
bundle = getIntent().getExtras();
String url = bundle.getString("url");
title = bundle.getString("title");
service_name.setText(title);
webView.loadUrl("/"+url);
webView.requestFocusFromTouch();
webView.getSettings().setCacheMode(WebSettings.LOAD_CACHE_ELSE_NETWORK);
webView.setWebViewClient(new WebViewClient(){
@Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);
return true;
}
});
webView.getSettings().setUseWideViewPort(true);
webView.getSettings().setSupportZoom(true);
webView.getSettings().setLoadWithOverviewMode(true);
webView.getSettings().setJavaScriptEnabled(true);
}
}
activity_apponitment,activity_bus,activity_weizhang,activity_city_state,activity_liviing_pay,activity_park等xml 文件布局,这里也是基本都一样
<LinearLayout 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:orientation="vertical"
tools:context=".activity.BusActivity">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<androidx.appcompat.widget.Toolbar
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/toolbar"
android:background="#0B84E4"/>
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="违章查询"
android:textColor="#fff"
android:id="@+id/service_name"
android:textStyle="bold"
android:textSize="20sp"
android:gravity="center"
android:layout_centerVertical="true"/>
RelativeLayout>
<WebView
android:layout_width="match_parent"
android:layout_height="200dp"
android:id="@+id/webView"/>
LinearLayout>
package com.example.myapp.bean;
import java.util.List;
/**
* @ProjectName: MyApp4
* @Package: com.example.myapp4.bean
* @ClassName: CommentBean
* @Description:
* @Author: liyingxia
* @CreateDate: 2021/4/3 23:57
*/
public class CommentBean {
private int total;
private int code;
private String msg;
private List<RowsDTO> rows;
public int getTotal() {
return total;
}
public void setTotal(int total) {
this.total = total;
}
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<RowsDTO> getRows() {
return rows;
}
public void setRows(List<RowsDTO> rows) {
this.rows = rows;
}
public static class RowsDTO {
private String createTime;
private Object updateBy;
private ParamsDTO params;
private String content;
private String nickName;
private String userName;
private String avatar;
public String getCreateTime() {
return createTime;
}
public void setCreateTime(String createTime) {
this.createTime = createTime;
}
public Object getUpdateBy() {
return updateBy;
}
public void setUpdateBy(Object updateBy) {
this.updateBy = updateBy;
}
public ParamsDTO getParams() {
return params;
}
public void setParams(ParamsDTO params) {
this.params = params;
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
public String getNickName() {
return nickName;
}
public void setNickName(String nickName) {
this.nickName = nickName;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getAvatar() {
return avatar;
}
public void setAvatar(String avatar) {
this.avatar = avatar;
}
public static class ParamsDTO {
}
@Override
public String toString() {
return "RowsDTO{" +
"createTime='" + createTime + '\'' +
", content='" + content + '\'' +
", nickName='" + nickName + '\'' +
", userName='" + userName + '\'' +
", avatar='" + avatar + '\'' +
'}';
}
public RowsDTO(String createTime, String content, String nickName, String userName, String avatar) {
this.createTime = createTime;
this.content = content;
this.nickName = nickName;
this.userName = userName;
this.avatar = avatar;
}
}
}
package com.example.myapp.bean;
import java.util.List;
/**
* @ProjectName: MyApp
* @Package: com.example.myapp.bean
* @ClassName: RecommendBean
* @Description:
* @Author: liyingxia
* @CreateDate: 2021/4/5 9:18
*/
public class RecommendBean {
private int total;
private int code;
private String msg;
private List<RowsDTO> rows;
public int getTotal() {
return total;
}
public void setTotal(int total) {
this.total = total;
}
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<RowsDTO> getRows() {
return rows;
}
public void setRows(List<RowsDTO> rows) {
this.rows = rows;
}
public static class RowsDTO {
/**
* searchValue : null
* createBy : null
* createTime : 2020-10-12 18:17:23
* updateBy : null
* updateTime : 2020-10-19 16:56:47
* remark : null
* params : {}
* id : 2
* serviceName : 城市地铁
* serviceDesc : 城市地铁路线
* serviceType : 1
* imgUrl : /profile/ditie.png
* pid : 1
* isRecommend : 1
* link : metro_query/index
*/
private String createTime;
private String updateTime;
private ParamsDTO params;
private int id;
private String serviceName;
private String serviceDesc;
private String serviceType;
private String imgUrl;
private int pid;
private int isRecommend;
private String link;
public String getCreateTime() {
return createTime;
}
public void setCreateTime(String createTime) {
this.createTime = createTime;
}
public String getUpdateTime() {
return updateTime;
}
public void setUpdateTime(String updateTime) {
this.updateTime = updateTime;
}
public ParamsDTO getParams() {
return params;
}
public void setParams(ParamsDTO params) {
this.params = params;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getServiceName() {
return serviceName;
}
public void setServiceName(String serviceName) {
this.serviceName = serviceName;
}
public String getServiceDesc() {
return serviceDesc;
}
public void setServiceDesc(String serviceDesc) {
this.serviceDesc = serviceDesc;
}
public String getServiceType() {
return serviceType;
}
public void setServiceType(String serviceType) {
this.serviceType = serviceType;
}
public String getImgUrl() {
return imgUrl;
}
public void setImgUrl(String imgUrl) {
this.imgUrl = imgUrl;
}
public int getPid() {
return pid;
}
public void setPid(int pid) {
this.pid = pid;
}
public int getIsRecommend() {
return isRecommend;
}
public void setIsRecommend(int isRecommend) {
this.isRecommend = isRecommend;
}
public String getLink() {
return link;
}
public void setLink(String link) {
this.link = link;
}
public static class ParamsDTO {
}
}
}
package com.example.myapp.bean;
/**
* @ProjectName: MyApp4
* @Package: com.example.myapp4.bean
* @ClassName: ResponseBean
* @Description: 请求响应结果
* @Author: liyingxia
* @CreateDate: 2021/4/3 19:31
*/
public class ResponseBean {
/**
* msg : 操作成功
* code : 200
*/
private String msg;
private String code;
public String getMsg() {
return msg;
}
public void setMsg(String msg) {
this.msg = msg;
}
public String getCode() {
return code;
}
public void setCode(String code) {
this.code = code;
}
@Override
public String toString() {
return "ResponseBean{" +
"msg='" + msg + '\'' +
", code=" + code +
'}';
}
}
package com.example.myapp.bean;
import java.util.List;
/**
* @ProjectName: MyApp
* @Package: com.example.myapp.bean
* @ClassName: ServiceBean
* @Description:
* @Author: liyingxia
* @CreateDate: 2021/4/23 10:03
*/
public class ServiceBean {
private int total;
private int code;
private String msg;
private List<RowsBean> rows;
public int getTotal() {
return total;
}
public void setTotal(int total) {
this.total = total;
}
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<RowsBean> getRows() {
return rows;
}
public void setRows(List<RowsBean> rows) {
this.rows = rows;
}
public static class RowsBean {
/**
* searchValue : null
* createBy : null
* createTime : 2020-10-12 18:17:23
* updateBy : null
* updateTime : 2020-10-19 16:56:47
* remark : null
* params : {}
* id : 2
* serviceName : 城市地铁
* serviceDesc : 城市地铁路线
* serviceType : 1
* imgUrl : /profile/ditie.png
* pid : 1
* isRecommend : 1
* link : metro_query/index
*/
private Object searchValue;
private Object createBy;
private String createTime;
private Object updateBy;
private String updateTime;
private Object remark;
private ParamsBean params;
private int id;
private String serviceName;
private String serviceDesc;
private String serviceType;
private String imgUrl;
private int pid;
private int isRecommend;
private String link;
public Object getSearchValue() {
return searchValue;
}
public void setSearchValue(Object searchValue) {
this.searchValue = searchValue;
}
public Object getCreateBy() {
return createBy;
}
public void setCreateBy(Object createBy) {
this.createBy = createBy;
}
public String getCreateTime() {
return createTime;
}
public void setCreateTime(String createTime) {
this.createTime = createTime;
}
public Object getUpdateBy() {
return updateBy;
}
public void setUpdateBy(Object updateBy) {
this.updateBy = updateBy;
}
public String getUpdateTime() {
return updateTime;
}
public void setUpdateTime(String updateTime) {
this.updateTime = updateTime;
}
public Object getRemark() {
return remark;
}
public void setRemark(Object remark) {
this.remark = remark;
}
public ParamsBean getParams() {
return params;
}
public void setParams(ParamsBean params) {
this.params = params;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getServiceName() {
return serviceName;
}
public void setServiceName(String serviceName) {
this.serviceName = serviceName;
}
public String getServiceDesc() {
return serviceDesc;
}
public void setServiceDesc(String serviceDesc) {
this.serviceDesc = serviceDesc;
}
public String getServiceType() {
return serviceType;
}
public void setServiceType(String serviceType) {
this.serviceType = serviceType;
}
public String getImgUrl() {
return imgUrl;
}
public void setImgUrl(String imgUrl) {
this.imgUrl = imgUrl;
}
public int getPid() {
return pid;
}
public void setPid(int pid) {
this.pid = pid;
}
public int getIsRecommend() {
return isRecommend;
}
public void setIsRecommend(int isRecommend) {
this.isRecommend = isRecommend;
}
public String getLink() {
return link;
}
public void setLink(String link) {
this.link = link;
}
public static class ParamsBean {
}
public RowsBean(String serviceName, String serviceDesc, String imgUrl, String link) {
this.serviceName = serviceName;
this.serviceDesc = serviceDesc;
this.imgUrl = imgUrl;
this.link = link;
}
@Override
public String toString() {
return "RowsBean{" +
"serviceName='" + serviceName + '\'' +
", serviceDesc='" + serviceDesc + '\'' +
", imgUrl='" + imgUrl + '\'' +
", link='" + link + '\'' +
'}';
}
}
}