前言
因为谷歌对android频繁的更新换代,每次在找一些实现方法的时候都发现其实已经过时了。虽然官网也有实现的办法,但或许是本地化的不足或者个别方法没有范例,有的看起来比较吃力,还得找一些简单的实例才能看懂用法,这篇博客就拿来放一下我用到的常用的不太好记住的方法吧
方法
1.获取res/values/colors中的颜色,getColor()
之前的方法:
context.getResource().getColor();//已弃用
context.getColor();//方法需要在API23以上才能用
替代方法:
ContextCompat.getColor(context,R.color.red);
2.onActivityResult(),根据intent跳转到别的activity并获取数据
原本的方法:
@Override
public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
}
现在的方法:
private final ActivityResultLauncher<Intent> resultLauncher =
registerForActivityResult(new ActivityResultContracts.StartActivityForResult(), result -> {
if (result != null && result.getResultCode() == Activity.RESULT_OK ) {
//todo
}
});
//在方法中调用launcher
private void getResult(){
resultLauncher.launch(intent)
}
这篇博客总结了Android开发中因版本更新导致的一些过时方法及其替代方案,包括如何在不同API级别下获取资源颜色,以及如何使用新的onActivityResult()处理数据返回。通过实例演示了ContextCompat.getColor()和ActivityResultLauncher的使用方法,帮助开发者更好地理解和适配新API。

414

被折叠的 条评论
为什么被折叠?



