美文网首页
2018-10-11【Android代码重构使用技巧】

2018-10-11【Android代码重构使用技巧】

作者: mahongyin | 来源:发表于2018-10-11 14:21 被阅读29次

1.代码重构

android:singleLine=”true”过时

解决方法:使用android:maxLines=”1”代替

(后来经证实,这个方法有坑,android:maxLines只能保证所有内容在只显示一行,但是任然可以换行输入)

在给TextView赋值时非Stringl类型的值使用”+”进行字符串拼接

例如:tvCount.setText(detail.getCount+”“)这样的代码会出现

Do not concatenate text displayed with setText. Use resource string with placeholders.

这样的警告

解决方法:使用String.valueOf()来代替,例如:tvCount.setText(String.valueOf(detail.getCount))

paddingStart替代paddingLeft,如果你的项目minSdk版本是17或以上在以前的layout代码中有可能会出现When you define paddingLeft you should probably also define paddingRight for right-to-left symmetry

取消通过new创建的集合框架里面的泛型

使用SharedPreferences的提交时apply代替commit,因为apply是异步的而commit是同步的

2.

我们在使用TextView显示内容的过程中,经常遇到需要显示的内容只有少许参数需要改变,比如:

距离过年还有xx天xx时xx秒,当我们在更新TextView的内容时,一般是这么写的:

TextView mTextView =this.findViewById(R.id.mTextView);

mTextView.setText("距离过年还有"+mDay+"天"+mMinute+"时"+mSecond+"秒");

如果你是用Android Studio开发的话,那么它应该送你以下的警告:

Do not concatenate text displayed with setText,use resource string with placeholders

[撇脚翻译:应使用资源字符串来显示文本占位符],这里所说的就是mDay、mMinute、mSecond这些变量了。

当然对于这些警告我们其实可以不理它们,它只是告诉我们这样写不规范,但如果我们要消除这个警告,

可以使用以下的实现:

string.xml中的资源声明

<string name="delay_time">距离过年还有%1$d天%2$d时%3$d秒</string>

在代码中的使用:

mTextView.setText(String.format(getResources().getString(R.string.delay_time),mDay,mMinute,mSecond));

常用格式:

%n$s--->n表示目前是第几个参数 (比如%1$s中的1代表第一个参数),s代表字符串

%n$d--->n表示目前是第几个参数 (比如%1$d中的1代表第一个参数),d代表整数

%n$f--->n表示目前是第几个参数 (比如%1$f中的1代表第一个参数),f代表浮点数

RadioButton设置默认选中

RadioButton 设置默认选中的效果不能使用

android:checked=true

以上代码会导致点击其他RadioButton后,会出现多个RadioButton被选中的情况,应该使用

<RadioGroup

 ....android:checkbutton="@+id/radio_btn_1"

  ....>  <RadioButton

            .....  android:id="@+id/radion_btn_1"

            ...../>

......</RadioGroup>

这样ID=radio_btn_1的radiobutton就会默认被选中

TextView 中Html 特效

<string name="msg_account_data"><DATA><![CDATA[<b><font color="red">%1$S</font></b>]]></DATA></string>

使用

mTextView.setText(Html.fromHtml(String.format(I18NData.getI18NString(R.string.msg_account_data), SizeUtils.moneyFenToYuan(amount))));

给Activity页面加上返回按钮

使用android:parentActivityName可以给页面加上返回按钮

<activity android:name=".activity.SettingActivity"

            android:label="@string/set_up"

            android:parentActivityName=".activity.SettingActivity"/>

去除ActionBar

style.xml

<style name="AppTheme.NoActionBar">

    <item name="windowNoTitle">true</item>

    <item name="windowActionBar">false</item>

    <item name="android:windowFullscreen">true</item>

    <item name="android:windowContentOverlay">@null</item>

</style>

使用

<activity

    ...

    android:theme="@style/AppTheme.NoActionBar">

</activity>

3.Android开发中,有哪些让你觉得相见恨晚的方法、类或接口?

相关文章

网友评论

      本文标题:2018-10-11【Android代码重构使用技巧】

      本文链接:https://www.haomeiwen.com/subject/azlbaftx.html