您的位置:首页 > 移动开发 > Android开发

Android中实用小技巧集锦

2015-12-20 00:35 489 查看
1、inflate的正确使用姿势

在Adapter中获取条目布局的时候,直接使用inflater.inflate(res, null)的方式获取view对象可能会丢失条目根目录参数,可以使用以下方法解决:

LayoutInflater inflater = LayoutInflater.from(context);
convertView = inflater.inflate(R.layout.item_list, parent, false);


经过测试(使用sdk版本23编译, 运行在4.3模拟器上),直接使用inflater.inflate(res, null)的方式获取view对象也没有丢失参数,可能与版本有关。

LayoutInflater是一切View解析的根基,它使用pull解析的方式,读取xml文件中配置的信息以创建view对象。当我们使用View.inflate的时候,本质上还是使用LayoutInflater,有源码可证:

public static View inflate(Context context, @LayoutRes int resource, ViewGroup root) {
LayoutInflater factory = LayoutInflater.from(context);
return factory.inflate(resource, root);
}


2、解决HttpClient使用报错问题

在Android6.0以后,谷歌移除了对apache的HttpClient的支持(推荐使用HttpURLConnection),如果需要用的话,可以在相应的module–>build.gradle–>android{ 中添加如下代码:

useLibrary ‘org.apache.http.legacy’

3、getWidth与getMeasuredWidth

getMeasuredWidth一般用在自定义view重写onLayout时、在我们用LayoutInflater动态加载view后想获得view的原始宽度时。使用前记得先调用measure方法。

已经布局完成之后,可以直接使用getWidth获取控件宽度。

getHeight和getMeasuredHeight同上。

今天先写这么多,有空再更新。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  android 实用技巧