本篇博客用于记录在Android开发中遇到的一些细小问题。由于每个问题都是细小而零碎的,所以记录在一篇博客中方便日后查找。
字符串处理
\n在TextView不正常显示换行
拿到了后台的Json数据,对Json数据进行处理后TextView无法将\n显示为换行,解决办法:
messageView.setText(message.replace("\\n", "\n"));
String和Int的互转
String转int:
1.) int i=Integer.parseInt(s); //直接使用静态方法,不会产生多余的对象,但会抛出异常
2.) int i = Integer.valueOf(my_str).intValue();Integer.valueOf(s) 相当于 new Integer(Integer.parseInt(s)),也会抛异常,但会多产生一个对象
字串转成 Double, Float, Long 的方法大同小异
Int转String:
1.) String s = String.valueOf(i);//直接使用String类的静态方法,只产生一个对象
2.) String s = Integer.toString(i);
3.) String s = "" + i; //会产生两个String对象
Double, Float, Long 转成字串的方法大同小异
参考文章:http://blog.csdn.net/memray/article/details/7312817/
控件小操作
Java设置Button颜色
btn.setBackgroundColor(getBaseContext().getResources().getColor(R.color.gray));
以上的方法不建议使用,因为getColor()方法已经过期。
可以使用下面这种方法:
bt.setBackgroundResource(R.drawable.ic_launcher);
Android 6.0+ RecyclerView嵌套在ScrollView中显示不全问题
终极解决办法是在RecyclerView的外部套上一层RelativeLayout
解决办法是在RecyclerView的外部套上一层RelativeLayout
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<android.support.v7.widget.RecyclerView
android:id="@+id/menuRv"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="@dimen/margin_16"
android:layout_marginRight="@dimen/margin_16"/>
</RelativeLayout>
参考:http://blog.csdn.net/u012862619/article/details/72638590
设置控件/布局参数
last.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, 500)); //宽、高
其他参数自查。
Button字母自动大写的解决
出现这个问题是因为Android 5.1+的SDK把Button的默认Style改了,样式默认把textAllCaps设置为true了,所以解决办法如下:
android:textAllCaps="false"
LinearLayout 中的子控件的居中
android:orientation="vertical"
表示该布局下的元素垂直排列
android:layout_gravity="center_horizontal"
表示该布局在父布局里水平居中,此时其父布局必须拥有android:orientation="vertical"
属性
android:gravity="center_horizontal"
表示该布局下的元素水平居中
android:layout_gravity="center_vertical"
表示该布局在父布局里垂直居中,此时其父布局必须应设置成android:orientation="horizontal"
属性(默认为该属性),且其父布局的高度应设置为android:layout_height="fill_parent"
属性。
TextView 长按复制
Android开发实现长按复制文本功能的方法很多:改写系统长按响应、EditView控件替换TextView的方法,自定义控件等等,总之都比较麻烦,而且效果也不好。
其实在布局文件的TextView控件属性中增加这么一句就行:android:textIsSelectable="true"
不过android sdk 11起才支持,v11以下则不行了。经测试,在Android4没问题,2.3的系统不行,大家可以根据需求针对性测试下。
RecyclerView android:layout_width=”match_parent”无效
这么写就可以了:
View view = mInflater.from(mContext).inflate(R.layout.item_fra_main2, parent, false);
这么写就不行哦:
View view = View.inflate(parent.getContext(), R.layout.item_fra_main2, null);