《第一行代码》看过已经有一段时间了,但是最后的酷欧天气实战却一直没有尝试,其实全书的精华都在这个实战项目里了,但是因为版本的更迭,虽然是按照书上的代码一步一步尝试,却也遇到了一些问题。
我把代码放在Github上了,可以参考一下。
https://github.com/Yx-u/CoolWeather
问题一:ProgressDialog被弃用
Android官方文档中写到:
This class was deprecated in API level 26. ProgressDialog is a modal
dialog, which prevents the user from interacting with the app. Instead
of using this class, you should use a progress indicator like
ProgressBar, which can be embedded in your app’s UI. Alternatively,
you can use a notification to inform the user of the task’s progress.
该类在API级别26中已被弃用。ProgressDialog是一个模式对话框,它阻止用户与应用程序交互。不要使用这个类,您应该使用ProgressBar这样的进度指示器,它可以嵌入到应用程序的UI中。或者,可以使用通知通知用户任务的进度。
ProgressDialog会禁止用户与app进行交互,所以被弃用了,那么我们如何替代呢?
替代方法:
ProgressBar + Dialog
ProgressBar的出现和消失
progressBar.setVisibility(View.VISIBLE); //To show ProgressBar
progressBar.setVisibility(View.GONE); // To Hide ProgressBar
当然也可以直接把ProgressDialog相关的代码删掉,不影响使用。
问题二:网络请求失败
在进行遍历省市县三级列表的时候,网络请求一直失败,无法显示数据,虽然知道问题的原因出在网络上,但是却不知道如何修正。
https://blog.csdn.net/kikii233/article/details/103830339
这篇文章给出了解决方法:
新建res/xml/network_security_config.xml
内容:
<?xml version="1.0" encoding="utf-8"?>
<network-security-config>
<base-config cleartextTrafficPermitted="true" />
</network-security-config>
在AndroidManifest.xml的application中添加android:networkSecurityConfig="@xml/network_security_config"
现在重新运行就可以了
问题三:PreferenceManager被弃用
虽然显示被弃用,但是如果继续使用还是没有影响。。。
问题四:刷新控件失效
在手动更新天气界面,使用下拉刷新功能时,书上使用的是SwipeRefreshLayout 控件,但是使用时一直标红,你会发现support.v4这个包已经没有了
最新版应该使用:
androidx.drawerlayout.widget.DrawerLayout
androidx.swiperefreshlayout.widget.SwipeRefreshLayout
在使用这个控件前需要导入依赖:
implementation 'androidx.swiperefreshlayout:swiperefreshlayout:1.1.0'
问题五:滑动菜单失效
这个问题和上一个问题一样,是support.v4包的原因,因为这个包已经失效了
换用androidx.drawerlayout.widget.DrawerLayout
就可以了,这个不需要添加依赖
完整的activity_weather.xml
代码
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width=