首页 文章 精选 留言 我的

精选列表

搜索[app开发],共10000篇文章
优秀的个人博客,低调大师

从0开始完成一款App】8.构建主页(2)

个人博客CoorChice,https://chenbingx.github.io/ ,最新文章将会首发CoorChice的博客,欢迎探索哦 ! 同时,搜索CoorChice关注我的微信公众号,同期文章也将会优先推送到公众号中,以提醒您有新鲜文章出炉。亦可在文章末尾扫描二维码关注。 封面.jpg 本系列文章列表 由于最近有点忙,所以这个系列的文章最近都没时间更新,断片的同学可以再看看前面的回顾一下,主要需要把该项目的结构设计回顾一下。 好了,言归正传。截止上一篇,我们已经把主页的Activity完成了,里面嵌套的Fragment的布局也完成了。下面我们需要一起来完成Fragment的Presenter和Model,以及Fragment中用于展示详细信息的RecyclerView的Adapter。完成这些,就可以看到我们预期的效果了。 Model模块 由于同属于天气请求,并且业务逻辑差别不大,所以我们可以直接把该Fragment的Model业务整合到之前的WeatherDataModel 中。 在这个Fragment中我们需要根据城市名称来获取相应的天气数据,当与定位城市相同时,我们就可以直接使用之前缓存好的数据,否则请求新的数据。 在WeatherDataModelApi中增加一个接口,因为功能类似,所以我们直接重载之前的接口就好。 void requestWeatherData(String cityName); //根据城市名称获取天气数据 相应的需要在WeatherDataModel实现上面接口的逻辑。 @Override public void requestWeatherData(String cityName) { WeatherData data; if (isGetCacheData(cityName)){ //先判断传入的名字是否和定位城市名字一样。 getCacheData(); //一样,获取缓存的天气数据 } else { getWeatherData(cityName); //不一样,从网络请求新数据 } } private boolean isGetCacheData(String cityName) { //这里我确定的规则是,当传入null、“”或定位城市名,都按定位城市名处理 return cityName == null || TextUtils.isEmpty(cityName) || DataCache.getInstance().getCurrentLocation().getCity().contains(cityName); } private void getCacheData() { WeatherData data; data = DataCache.getInstance().getWeatherData(); //从缓存中取出定位城市天气数据 if (requestWeatherDataListener != null) { //这是一个回调,待会儿咱们再来聊聊这个回调 requestWeatherDataListener.onRequestWeatherDataSuccess(data); // 请求成功 } } private void getWeatherData(String cityname) { //根据城市名称请求数据 ApiClient.getWeatherData(cityname, data -> { LogUtils.i("requestWeatherData: " + GsonUtils.getSingleInstance().toJson(data)); if (requestWeatherDataListener != null) { requestWeatherDataListener.onRequestWeatherDataSuccess(data); // 请求成功 } }, message -> { if (requestWeatherDataListener != null) { requestWeatherDataListener.onRequestWeatherDataFailure(message); } }); } 好了现在我们已经可以在Presenter中调用Model的方法了,但是由于数据请求是异步完成,所以我们使用返回值的方式返回数据很不方便,于是回调机制就再次需要被使用。 因为我们的Presenter只持有Model的接口,所以需要把添加回调的方法定义在WeatherDataModelApi中。其次,由于是专用回调,干脆把监听回调也写到其中。 void setRequestWeatherDataListener(RequestWeatherDataListener requestWeatherDataListener); //设置回调的接口 // 因为每个Model可能需要请求多个接口,所以每个回调可能不同,就把它写到内部了 interface RequestWeatherDataListener { //成功获取数据的回调 void onRequestWeatherDataSuccess(WeatherData data); //获取数据失败的回调 void onRequestWeatherDataFailure(String message); } 接下来,自然是要在Model中实现一下setRequestWeatherDataListener() 。就是一个普通的set方法,我就不展示。至于回调的调用时机,在上面的代码中已经包含了。 Presenter模块 完成了Model模块就可以接着来编写Presenter模块了。 首先自然是要先写接口喽WeatherDetailFragmentPresenterApi public interface WeatherDetailFragmentPresenterApi extends BasePresenter { void getWeatherData(String cityName); } 接着完成WeatherDetailFragmentPresenter,上个完整的。可以看到,只要按照约定好的结构填内容就行。记住要依赖抽象,不要依赖具体。 public class WeatherDetailFragmentPresenter implements WeatherDetailFragmentPresenterApi, WeatherDataModelApi.RequestWeatherDataListener { private WeatherDetailFragmentView view; private WeatherDataModelApi model; public WeatherDetailFragmentPresenter(WeatherDetailFragmentView view) { this.view = view; model = new WeatherDataModel(); //我们在这里把回调添加了 model.setRequestWeatherDataListener(this); } public void getWeatherData(String cityName){ model.requestWeatherData(cityName); //请求数据 } @Override public void onRequestWeatherDataSuccess(WeatherData data) { view.onWeatherDataUpdate(data); //通知View更新UI } @Override public void onRequestWeatherDataFailure(String message) { } @Override public void destroy() { //记得销毁时把对象显示的释放一下 model.setRequestWeatherDataListener(null); model = null; view = null; } } Adapter 接下来看看比较重要的一个对象,Adapter。 首先看一下效果。 RecyclerView效果 上一篇我已经展示了我们RecyclerView使用的是LinearLayoutManager布局管理器,因为其实这个结构也并复杂,我把它分成上下两个部分。 上半部分是一条条简略的天气信息。 上半部分 item_future_weather_info.xml <?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="40dp" android:orientation="horizontal" tools:background="@color/opacity_9_yellow" > <TextView android:id="@+id/week" android:layout_width="wrap_content" android:layout_height="match_parent" android:gravity="center" tools:text="星期日" android:layout_marginLeft="10dp" android:textColor="@color/white" /> <ImageView android:id="@+id/weather_pic" android:layout_width="match_parent" android:layout_height="match_parent" android:src="@drawable/sun" android:padding="10dp" /> <TextView android:id="@+id/low_temperature" android:layout_width="wrap_content" android:layout_height="match_parent" android:layout_alignParentRight="true" android:gravity="center" tools:text="-7" android:layout_marginRight="10dp" android:textColor="@color/gray" /> <TextView android:id="@+id/high_temperature" android:layout_width="wrap_content" android:layout_height="match_parent" android:layout_alignParentTop="true" android:layout_toStartOf="@+id/low_temperature" android:layout_marginRight="15dp" android:gravity="center" android:textColor="@color/white" tools:text="10"/> </RelativeLayout> 下半部分 item_today_detail_info.xml 下半部分 <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:background="@color/transparent" android:orientation="vertical" tools:background="@color/black" > <include layout="@layout/line_white"/> <TextView android:id="@+id/chuanyi" android:layout_width="match_parent" android:layout_height="wrap_content" android:textColor="@color/white" tools:text="天气冷,建议着棉服、羽绒服、皮夹克加羊毛衫等冬季服装。年老体弱者宜着厚棉衣、冬大衣或厚羽绒服。" android:padding="10dp" /> <include layout="@layout/line_white"/> <LinearLayout android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="horizontal" android:padding="10dp" > <LinearLayout android:layout_width="0dp" android:layout_height="match_parent" android:layout_weight="1" android:orientation="vertical" android:paddingRight="10dp" > <TextView android:id="@+id/update_time" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="right" android:text="更新时间:" android:textColor="@color/white" /> <TextView android:id="@+id/moon" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="right" android:text="农历:" android:textColor="@color/white" /> <TextView android:id="@+id/wind_direct" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="right" android:layout_marginTop="10dp" android:text="风向:" android:textColor="@color/white" /> <TextView android:id="@+id/wind_power" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="right" android:text="等级:" android:textColor="@color/white" /> <TextView android:id="@+id/air_quality_index" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="right" android:layout_marginTop="10dp" android:text="空气质量指数:" android:textColor="@color/white" /> <TextView android:id="@+id/air_quality" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="right" android:text="空气质量:" android:textColor="@color/white" /> </LinearLayout> <LinearLayout android:layout_width="0dp" android:layout_height="match_parent" android:layout_weight="1" android:orientation="vertical" > <TextView android:id="@+id/update_time_data" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="left" android:paddingLeft="10dp" android:textColor="@color/white" tools:text="2016年12月05日16时" /> <TextView android:id="@+id/moon_data" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="left" android:paddingLeft="10dp" android:textColor="@color/white" tools:text="十一月初七" /> <TextView android:id="@+id/wind_direct_data" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="left" android:paddingLeft="10dp" android:paddingTop="10dp" android:textColor="@color/white" tools:text="西北风" /> <TextView android:id="@+id/wind_power_data" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="left" android:paddingLeft="10dp" android:textColor="@color/white" tools:text="4级" /> <TextView android:id="@+id/air_quality_index_data" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="left" android:paddingLeft="10dp" android:paddingTop="10dp" android:textColor="@color/white" tools:text="38" /> <TextView android:id="@+id/air_quality_data" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="left" android:paddingLeft="10dp" android:textColor="@color/white" tools:text="优" /> </LinearLayout> </LinearLayout> </LinearLayout> 下面看看Adapter,主要就是用getItemViewType() 区分一下Item的类型就行 public class FutureWeathersAdapter extends RecyclerView.Adapter { public static final int WEATHER_ITEM = 1; public static final int TODAY_INFO_ITEM = 3; private Context mContext; private List<Weather> weathers = new ArrayList<>(); private WeatherData.Data data; public FutureWeathersAdapter(Context mContext, WeatherData.Data data) { this.mContext = mContext; this.data = data; this.weathers.addAll(data.getWeather()); //为了避免在其它地方错误的数据操作,这里采用addAll()的方法来添加数据到Adapter中专门的集合 } @Override public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { if (viewType == WEATHER_ITEM) { //天气简略信息 return new BaseItemViewHolder(new FutureWeatherItem(mContext)); } else if(viewType == TODAY_INFO_ITEM){ //今天的详细信息 return new BaseItemViewHolder(new TodayDetailInfoItem(mContext)); } else { return null; } } @Override public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) { if (getItemViewType(position) == WEATHER_ITEM){ ((FutureWeatherItem)holder.itemView).setData(weathers.get(position), position); } else if (getItemViewType(position) == TODAY_INFO_ITEM){ ((TodayDetailInfoItem)holder.itemView).setData(data, position); } } @Override public int getItemViewType(int position) { if (position < weathers.size()){ return WEATHER_ITEM; } else if (position == weathers.size()){ return TODAY_INFO_ITEM; } else { return 0; } } @Override public int getItemCount() { return weathers.size() + 1; } public void updateData(WeatherData.Data data){ this.data = data; this.weathers.clear(); this.weathers.addAll(data.getWeather()); notifyDataSetChanged(); } } ItemView通过BaseItemViewHolder 创建,就是填充数据,没什么特别的。具体的请异步GitHub看这一部分代码。 FutureWeatherItem TodayDetailInfoItem 好了,现在我们已经完成了效果图的需求。这个项目最重要的几个部分已经基本完成了。后面就是迭代优化了。 项目地址GitHub CoorChice的公众号

优秀的个人博客,低调大师

从0开始完成一款App】8.构建主页(1)

个人博客CoorChice,https://chenbingx.github.io/ ,最新文章将会首发CoorChice的博客,欢迎探索哦 ! 同时,搜索CoorChice关注我的微信公众号,同期文章也将会优先推送到公众号中,以提醒您有新鲜文章出炉。亦可在文章末尾扫描二维码关注。 封面.jpg 本系列文章列表 截止上一篇,我们已经完成了欢迎页,并且成功的请求到了定位地点的天气数据,并且缓存起来。本篇我们将开始构建我们的核心主页,它用于展示天气数据。 主页需求 能够展示未来几天的天气; 能够展示当日的详细天气情况; 能够展示多地天气。 暂时先这几条,我们后面还可以再添加。现在我们开始着手实现这几个需求。 实现需求 根据以上需求,我们不但需要展示一天的详细数据和未来几天的天气数据,还要具备展示多地天气数据。所以大概可以设计一下,使用列表控件 来展示一个地区的详细数据,使用ViewPager 来展示不同地区的详细数据。话不多说,来看看这样的效果图。 效果图 主要xml文件 这个页面很简单,它由Activity和Fragment构成。Fragments被放到了ViewPager中。 下面来看看各个布局文件。 Activity.xml <?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:id="@+id/activity_main" android:layout_width="match_parent" android:layout_height="match_parent" android:background="@color/themeBlueDeep" android:clipChildren="false" android:gravity="center" tools:background="@color/themeBlueDeep" tools:context="com.chenbing.oneweather.View.activitys.MainActivity" > //用来容纳Fragment <android.support.v4.view.ViewPager android:id="@+id/pager_container" android:layout_width="match_parent" android:layout_height="match_parent" android:layout_above="@+id/bottom_opration" android:layout_alignParentStart="true" android:background="@color/transparent" tools:background="@color/opacity_7_white" /> //后期会在底部添加操作栏,所以先留出位置。 <RelativeLayout android:id="@+id/bottom_opration" android:layout_width="match_parent" android:layout_height="46dp" android:background="@color/transparent" tools:background="@color/opacity_5_red" android:layout_alignParentBottom="true" android:layout_alignParentStart="true"> <include layout="@layout/line_white"/> <ImageView android:id="@+id/right_button" android:layout_width="wrap_content" android:layout_height="match_parent" android:padding="8dp" tools:src="@drawable/sun" /> <LinearLayout android:layout_width="match_parent" android:layout_height="match_parent" android:layout_toLeftOf="@+id/left_button" android:layout_toRightOf="@+id/right_button" > </LinearLayout> <ImageView android:id="@+id/left_button" android:layout_width="wrap_content" android:layout_height="match_parent" android:layout_alignParentRight="true" android:padding="8dp" tools:src="@drawable/sun" /> </RelativeLayout> </RelativeLayout> Fragment.xml <?xml version="1.0" encoding="utf-8"?> <FrameLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:background="@color/colorPrimary" > <LinearLayout android:id="@+id/header" android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="vertical" > <TextView android:id="@+id/city_name" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginTop="60dp" android:gravity="center" android:textColor="@color/white" android:textSize="35sp" tools:text="北京市" /> <TextView android:id="@+id/weather_info" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginTop="5dp" android:gravity="center" android:textColor="@color/white" android:textSize="14sp" tools:text="多云" /> <TextView android:id="@+id/air_quality" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginTop="2dp" android:gravity="center" android:textColor="@color/white" android:textSize="14sp" tools:text="空气质量:危害健康" /> <TextView android:id="@+id/temperature" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginTop="0dp" android:gravity="center_horizontal" android:textColor="@color/white" android:textSize="80sp" tools:text="3°"/> </LinearLayout> //用来装未来天气数据和当日详细信息 <android.support.v7.widget.RecyclerView android:id="@+id/recyclerView" android:layout_width="match_parent" android:layout_height="match_parent" android:clipToPadding="false" android:paddingTop="270dp" tools:listitem="@layout/item_future_weather_info" /> </FrameLayout> Activity 这个Activity的结构和之前的欢迎页差不多。 View模块 首先创建MainActivity的接口。 public interface MainActivityView extends MvpView { } 继承接口,创建Activity。 public class MainActivity extends BaseActivity implements MainActivityView { @BindView(R.id.pager_container) ViewPager pagerContainer; private MainActivityPresenterApi presenter; //依赖Presenter的抽象 private List<BaseFragment> fragments = new ArrayList<>(); //这个数组用来装每个地区的天气页面 @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); presenter = new MainActivityPresenter(this); ButterKnife.bind(this); initData(); initView(); addListener(); } @Override protected void initData() { fragments.add(WeatherDetailFragment.newInstance(null)); //创建Fragment //这里之所以穿Null是因为我在后面处理时,把默认天气数据设置为定位地区的 } @Override protected void initView() { setWindowProperties(); //设置ViewPager的适配器 pagerContainer.setAdapter(new FragmentPagerAdapter(getSupportFragmentManager()) { @Override public Fragment getItem(int position) { return fragments.get(position); } @Override public int getCount() { return fragments.size(); } }); pagerContainer.setPageTransformer(false, new ZoomOutPageTransformer()); } private void setWindowProperties() { // 实现透明状态栏 getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS | WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION); getWindow().setFormat(PixelFormat.TRANSPARENT); } @Override protected void addListener() { } @Override protected BasePresenter getPresenter() { return presenter; } } Presenter模块 由于目前Activity本身并不处理什么任务,所以Presenter中还没内容,但是我们任然要按照架构写,因为后面可能会添加东西进去。 //Presenter接口 public interface MainActivityPresenterApi extends BasePresenter { } //Presenter实现,因为暂时不处理事物,所以先不写Model了 public class MainActivityPresenter implements MainActivityPresenterApi { private MainActivityView view; public MainActivityPresenter(MainActivityView view) { this.view = view; } @Override public void destroy() { view = null; } } Fragment 上面代码中可以看到,我们已经创建了一个Fragment,下面就来看看这个Fragment是什么样的。 Fragment同样需要按照MVP模式来,首先需要改造一下BaseFragment。 public abstract class BaseFragment extends Fragment { abstract protected void initData(); abstract protected void initView(); abstract protected void addListener(); /** * 创建Presenter后必须重写这个方法,将其作为返回值 */ abstract protected BasePresenter getPresenter(); @Override public void onViewCreated(View view, @Nullable Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); view.setClickable(true); //这个操作是为了防止Fragment出现点透Bug } @Override public void onDestroyView() { super.onDestroyView(); if (getPresenter() != null){ getPresenter().destroy(); //销毁Presenter,避免Activity对象因被Presenter持有而不能被销毁 } } } View模块 Fragment的接口。 public interface WeatherDetailFragmentView extends MvpView { void onWeatherDataUpdate(WeatherData data); //通知View更新数据,这个方法供Presenter调用 } 实现Fragment,包含了交互操作。 public class WeatherDetailFragment extends BaseFragment implements WeatherDetailFragmentView { public static final String CITY_NAME = "city_name"; @BindView(R.id.header) ViewGroup header; @BindView(R.id.city_name) TextView cityName; @BindView(R.id.weather_info) TextView weatherInfo; @BindView(R.id.air_quality) TextView airQuality; @BindView(R.id.temperature) TextView temperature; @BindView(R.id.recyclerView) RecyclerView recyclerView; private WeatherDetailFragmentPresenterApi presenter; //依赖Presenter的抽象 private WeatherData data; private FutureWeathersAdapter adapter; private int totalDy; private int alphaReferenceValue; public static BaseFragment newInstance(String cityName) { //用静态方法创建Fragment WeatherDetailFragment instance = new WeatherDetailFragment(); Bundle args = new Bundle(); args.putString(CITY_NAME, cityName); //储存需要显示的地区名字在Fragment的Argument中 instance.setArguments(args); return instance; } @Nullable @Override public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { View rootView = inflater.inflate(R.layout.fragment_weather_detail, container, false); ButterKnife.bind(this, rootView); presenter = new WeatherDetailFragmentPresenter(this); //创建Fragment的Presenter initData(); initView(); addListener(); return rootView; } @Override protected void initData() { String cityName = getArguments().getString(CITY_NAME); presenter.getWeatherData(cityName); //请求天气数据 } @Override protected void initView() { //看上面效果图,我们只需要使用LinearLayoutManager就可以了 recyclerView.setLayoutManager( new LinearLayoutManager(getActivity(), LinearLayoutManager.VERTICAL, false)); recyclerView.setItemAnimator(new DefaultItemAnimator()); } @Override protected void addListener() { listenRecyclerView(); temperature.getViewTreeObserver() .addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() { @Override public void onGlobalLayout() { computeAlphaReferenceValue(); temperature.getViewTreeObserver().removeOnGlobalLayoutListener(this); } }); } private void computeAlphaReferenceValue() { //下面是在计算设置温度TextView的Alpha值的参考值,效果是在RecyclerView的第一个Item滑动到温度TextView的1/8时,温度TextView刚好完全透明 int temperatureY = temperature.getBottom(); int temperatureHeight = temperature.getMeasuredHeight(); int recyclerViewPaddingTop = recyclerView.getPaddingTop(); alphaReferenceValue = recyclerViewPaddingTop - temperatureY + temperatureHeight / 8; } private void listenRecyclerView() { recyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() { @Override public void onScrolled(RecyclerView recyclerView, int dx, int dy) { totalDy -= dy; //记录RecyclerView滑动的距离,上滑为负,下滑为正 float translationY = (float) (totalDy * 0.3); //取滑动距离的30%来移动上半部分View才能造成层次感 header.setTranslationY(translationY); //设置整个上半部分View的TranslationY,实现图中的滑动效果。 //translationY初始值为0,负值向上移动,正值向下移动,与Android坐标系的方向是一致的 float alpha = 1 - (float) (Math.abs(totalDy * 0.3)) / alphaReferenceValue; temperature.setAlpha(alpha); //设置Alpha值 super.onScrolled(recyclerView, dx, dy); } }); } @Override protected BasePresenter getPresenter() { return presenter; } @Override public void onWeatherDataUpdate(WeatherData data) { if (data != null) { updateView(data.getData()); } } private void updateView(WeatherData.Data data) { setHeaderView(data); setRecyclerView(data); } private void setHeaderView(WeatherData.Data data) { String cityName = data.getRealtime().getCity_name(); this.cityName.setText(cityName); String weatherInfo = data.getRealtime().getWeather().getInfo(); this.weatherInfo.setText(weatherInfo); String airQualityStrFormat = getString(R.string.air_quality); String airQuality = String.format(airQualityStrFormat, data.getPm25().getPm25().getQuality()); this.airQuality.setText(airQuality); String temperatureFormat = getString(R.string.temperature); String temperature = String.format(temperatureFormat, data.getRealtime().getWeather().getTemperature()); this.temperature.setText(temperature); } private void setRecyclerView(WeatherData.Data data) { if (data == null) { return; } if (adapter == null) { recyclerView.setAdapter(new FutureWeathersAdapter(getActivity(), data)); //在这里才创建RecyclerView的Adapter } else { adapter.updateData(data); } } } 由于篇幅问题,本篇先讲到这。后面的文章中我们在一起完成Fragment的Presenter、Model,以及编写RecyclerView的Adapter。 本项目已上传至GitHub,详细源码请到GitHub查看。 项目地址GitHub 截止上一篇,我们已经完成了欢迎页,并且成功的请求到了定位地点的天气数据,并且缓存起来。本篇我们将开始构建我们的核心主页,它用于展示天气数据。 主页需求 能够展示未来几天的天气; 能够展示当日的详细天气情况; 能够展示多地天气。 暂时先这几条,我们后面还可以再添加。现在我们开始着手实现这几个需求。 实现需求 根据以上需求,我们不但需要展示一天的详细数据和未来几天的天气数据,还要具备展示多地天气数据。所以大概可以设计一下,使用列表控件 来展示一个地区的详细数据,使用ViewPager 来展示不同地区的详细数据。话不多说,来看看这样的效果图。 效果图 主要xml文件 这个页面很简单,它由Activity和Fragment构成。Fragments被放到了ViewPager中。 下面来看看各个布局文件。 Activity.xml <?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:id="@+id/activity_main" android:layout_width="match_parent" android:layout_height="match_parent" android:background="@color/themeBlueDeep" android:clipChildren="false" android:gravity="center" tools:background="@color/themeBlueDeep" tools:context="com.chenbing.oneweather.View.activitys.MainActivity" > //用来容纳Fragment <android.support.v4.view.ViewPager android:id="@+id/pager_container" android:layout_width="match_parent" android:layout_height="match_parent" android:layout_above="@+id/bottom_opration" android:layout_alignParentStart="true" android:background="@color/transparent" tools:background="@color/opacity_7_white" /> //后期会在底部添加操作栏,所以先留出位置。 <RelativeLayout android:id="@+id/bottom_opration" android:layout_width="match_parent" android:layout_height="46dp" android:background="@color/transparent" tools:background="@color/opacity_5_red" android:layout_alignParentBottom="true" android:layout_alignParentStart="true"> <include layout="@layout/line_white"/> <ImageView android:id="@+id/right_button" android:layout_width="wrap_content" android:layout_height="match_parent" android:padding="8dp" tools:src="@drawable/sun" /> <LinearLayout android:layout_width="match_parent" android:layout_height="match_parent" android:layout_toLeftOf="@+id/left_button" android:layout_toRightOf="@+id/right_button" > </LinearLayout> <ImageView android:id="@+id/left_button" android:layout_width="wrap_content" android:layout_height="match_parent" android:layout_alignParentRight="true" android:padding="8dp" tools:src="@drawable/sun" /> </RelativeLayout> </RelativeLayout> Fragment.xml <?xml version="1.0" encoding="utf-8"?> <FrameLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:background="@color/colorPrimary" > <LinearLayout android:id="@+id/header" android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="vertical" > <TextView android:id="@+id/city_name" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginTop="60dp" android:gravity="center" android:textColor="@color/white" android:textSize="35sp" tools:text="北京市" /> <TextView android:id="@+id/weather_info" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginTop="5dp" android:gravity="center" android:textColor="@color/white" android:textSize="14sp" tools:text="多云" /> <TextView android:id="@+id/air_quality" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginTop="2dp" android:gravity="center" android:textColor="@color/white" android:textSize="14sp" tools:text="空气质量:危害健康" /> <TextView android:id="@+id/temperature" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginTop="0dp" android:gravity="center_horizontal" android:textColor="@color/white" android:textSize="80sp" tools:text="3°"/> </LinearLayout> //用来装未来天气数据和当日详细信息 <android.support.v7.widget.RecyclerView android:id="@+id/recyclerView" android:layout_width="match_parent" android:layout_height="match_parent" android:clipToPadding="false" android:paddingTop="270dp" tools:listitem="@layout/item_future_weather_info" /> </FrameLayout> Activity 这个Activity的结构和之前的欢迎页差不多。 View模块 首先创建MainActivity的接口。 public interface MainActivityView extends MvpView { } 继承接口,创建Activity。 public class MainActivity extends BaseActivity implements MainActivityView { @BindView(R.id.pager_container) ViewPager pagerContainer; private MainActivityPresenterApi presenter; //依赖Presenter的抽象 private List<BaseFragment> fragments = new ArrayList<>(); //这个数组用来装每个地区的天气页面 @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); presenter = new MainActivityPresenter(this); ButterKnife.bind(this); initData(); initView(); addListener(); } @Override protected void initData() { fragments.add(WeatherDetailFragment.newInstance(null)); //创建Fragment //这里之所以穿Null是因为我在后面处理时,把默认天气数据设置为定位地区的 } @Override protected void initView() { setWindowProperties(); //设置ViewPager的适配器 pagerContainer.setAdapter(new FragmentPagerAdapter(getSupportFragmentManager()) { @Override public Fragment getItem(int position) { return fragments.get(position); } @Override public int getCount() { return fragments.size(); } }); pagerContainer.setPageTransformer(false, new ZoomOutPageTransformer()); } private void setWindowProperties() { // 实现透明状态栏 getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS | WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION); getWindow().setFormat(PixelFormat.TRANSPARENT); } @Override protected void addListener() { } @Override protected BasePresenter getPresenter() { return presenter; } } Presenter模块 由于目前Activity本身并不处理什么任务,所以Presenter中还没内容,但是我们任然要按照架构写,因为后面可能会添加东西进去。 //Presenter接口 public interface MainActivityPresenterApi extends BasePresenter { } //Presenter实现,因为暂时不处理事物,所以先不写Model了 public class MainActivityPresenter implements MainActivityPresenterApi { private MainActivityView view; public MainActivityPresenter(MainActivityView view) { this.view = view; } @Override public void destroy() { view = null; } } Fragment 上面代码中可以看到,我们已经创建了一个Fragment,下面就来看看这个Fragment是什么样的。 Fragment同样需要按照MVP模式来,首先需要改造一下BaseFragment。 public abstract class BaseFragment extends Fragment { abstract protected void initData(); abstract protected void initView(); abstract protected void addListener(); /** * 创建Presenter后必须重写这个方法,将其作为返回值 */ abstract protected BasePresenter getPresenter(); @Override public void onViewCreated(View view, @Nullable Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); view.setClickable(true); //这个操作是为了防止Fragment出现点透Bug } @Override public void onDestroyView() { super.onDestroyView(); if (getPresenter() != null){ getPresenter().destroy(); //销毁Presenter,避免Activity对象因被Presenter持有而不能被销毁 } } } View模块 Fragment的接口。 public interface WeatherDetailFragmentView extends MvpView { void onWeatherDataUpdate(WeatherData data); //通知View更新数据,这个方法供Presenter调用 } 实现Fragment,包含了交互操作。 public class WeatherDetailFragment extends BaseFragment implements WeatherDetailFragmentView { public static final String CITY_NAME = "city_name"; @BindView(R.id.header) ViewGroup header; @BindView(R.id.city_name) TextView cityName; @BindView(R.id.weather_info) TextView weatherInfo; @BindView(R.id.air_quality) TextView airQuality; @BindView(R.id.temperature) TextView temperature; @BindView(R.id.recyclerView) RecyclerView recyclerView; private WeatherDetailFragmentPresenterApi presenter; //依赖Presenter的抽象 private WeatherData data; private FutureWeathersAdapter adapter; private int totalDy; private int alphaReferenceValue; public static BaseFragment newInstance(String cityName) { //用静态方法创建Fragment WeatherDetailFragment instance = new WeatherDetailFragment(); Bundle args = new Bundle(); args.putString(CITY_NAME, cityName); //储存需要显示的地区名字在Fragment的Argument中 instance.setArguments(args); return instance; } @Nullable @Override public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { View rootView = inflater.inflate(R.layout.fragment_weather_detail, container, false); ButterKnife.bind(this, rootView); presenter = new WeatherDetailFragmentPresenter(this); //创建Fragment的Presenter initData(); initView(); addListener(); return rootView; } @Override protected void initData() { String cityName = getArguments().getString(CITY_NAME); presenter.getWeatherData(cityName); //请求天气数据 } @Override protected void initView() { //看上面效果图,我们只需要使用LinearLayoutManager就可以了 recyclerView.setLayoutManager( new LinearLayoutManager(getActivity(), LinearLayoutManager.VERTICAL, false)); recyclerView.setItemAnimator(new DefaultItemAnimator()); } @Override protected void addListener() { listenRecyclerView(); temperature.getViewTreeObserver() .addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() { @Override public void onGlobalLayout() { computeAlphaReferenceValue(); temperature.getViewTreeObserver().removeOnGlobalLayoutListener(this); } }); } private void computeAlphaReferenceValue() { //下面是在计算设置温度TextView的Alpha值的参考值,效果是在RecyclerView的第一个Item滑动到温度TextView的1/8时,温度TextView刚好完全透明 int temperatureY = temperature.getBottom(); int temperatureHeight = temperature.getMeasuredHeight(); int recyclerViewPaddingTop = recyclerView.getPaddingTop(); alphaReferenceValue = recyclerViewPaddingTop - temperatureY + temperatureHeight / 8; } private void listenRecyclerView() { recyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() { @Override public void onScrolled(RecyclerView recyclerView, int dx, int dy) { totalDy -= dy; //记录RecyclerView滑动的距离,上滑为负,下滑为正 float translationY = (float) (totalDy * 0.3); //取滑动距离的30%来移动上半部分View才能造成层次感 header.setTranslationY(translationY); //设置整个上半部分View的TranslationY,实现图中的滑动效果。 //translationY初始值为0,负值向上移动,正值向下移动,与Android坐标系的方向是一致的 float alpha = 1 - (float) (Math.abs(totalDy * 0.3)) / alphaReferenceValue; temperature.setAlpha(alpha); //设置Alpha值 super.onScrolled(recyclerView, dx, dy); } }); } @Override protected BasePresenter getPresenter() { return presenter; } @Override public void onWeatherDataUpdate(WeatherData data) { if (data != null) { updateView(data.getData()); } } private void updateView(WeatherData.Data data) { setHeaderView(data); setRecyclerView(data); } private void setHeaderView(WeatherData.Data data) { String cityName = data.getRealtime().getCity_name(); this.cityName.setText(cityName); String weatherInfo = data.getRealtime().getWeather().getInfo(); this.weatherInfo.setText(weatherInfo); String airQualityStrFormat = getString(R.string.air_quality); String airQuality = String.format(airQualityStrFormat, data.getPm25().getPm25().getQuality()); this.airQuality.setText(airQuality); String temperatureFormat = getString(R.string.temperature); String temperature = String.format(temperatureFormat, data.getRealtime().getWeather().getTemperature()); this.temperature.setText(temperature); } private void setRecyclerView(WeatherData.Data data) { if (data == null) { return; } if (adapter == null) { recyclerView.setAdapter(new FutureWeathersAdapter(getActivity(), data)); //在这里才创建RecyclerView的Adapter } else { adapter.updateData(data); } } } 由于篇幅问题,本篇先讲到这。后面的文章中我们在一起完成Fragment的Presenter、Model,以及编写RecyclerView的Adapter。 本项目已上传至GitHub,详细源码请到GitHub查看。 项目地址GitHub CoorChice的公众号

资源下载

更多资源
优质分享App

优质分享App

近一个月的开发和优化,本站点的第一个app全新上线。该app采用极致压缩,本体才4.36MB。系统里面做了大量数据访问、缓存优化。方便用户在手机上查看文章。后续会推出HarmonyOS的适配版本。

Mario

Mario

马里奥是站在游戏界顶峰的超人气多面角色。马里奥靠吃蘑菇成长,特征是大鼻子、头戴帽子、身穿背带裤,还留着胡子。与他的双胞胎兄弟路易基一起,长年担任任天堂的招牌角色。

Rocky Linux

Rocky Linux

Rocky Linux(中文名:洛基)是由Gregory Kurtzer于2020年12月发起的企业级Linux发行版,作为CentOS稳定版停止维护后与RHEL(Red Hat Enterprise Linux)完全兼容的开源替代方案,由社区拥有并管理,支持x86_64、aarch64等架构。其通过重新编译RHEL源代码提供长期稳定性,采用模块化包装和SELinux安全架构,默认包含GNOME桌面环境及XFS文件系统,支持十年生命周期更新。

Sublime Text

Sublime Text

Sublime Text具有漂亮的用户界面和强大的功能,例如代码缩略图,Python的插件,代码段等。还可自定义键绑定,菜单和工具栏。Sublime Text 的主要功能包括:拼写检查,书签,完整的 Python API , Goto 功能,即时项目切换,多选择,多窗口等等。Sublime Text 是一个跨平台的编辑器,同时支持Windows、Linux、Mac OS X等操作系统。

用户登录
用户注册
修改密码
忘记密码