android强制转换整形,android中通过辅助类解决findViewById需要对返回值强制类型转换的问题...

1.android中findViewById需要对返回值强制类型转换的问题描述

findViewById的返回值是view类型,通常开发中,我们需要将其强制转换成实际类型,输入麻烦、代码丑陋:

@Override

protected void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.activity_main);

TextView textView = (TextView)findViewById(R.id.my_textview);

ImageView imageView = (ImageView)findViewById(R.id.my_imageview);

ListView listView = (ListView)findViewById(R.id.my_listview);

}

2.Android解决使用findViewById时需要对返回值进行类型转换问题的辅助类ViewFinder

ViewFinder类的核心是将view的id保存到SparseArray类型的mViewMap变量中,方便后面引用,还有就是类型转换。

import android.content.Context;

import android.util.SparseArray;

import android.view.LayoutInflater;

import android.view.View;

public final class ViewFinder {

static LayoutInflater mInflater;

/**

* 每项的View的sub view Map

*/

private static SparseArray mViewMap = new SparseArray();

/**

* Content View

*/

static View mContentView;

/**

* 初始化ViewFinder, 实际上是获取到该页面的ContentView.

*

* @param context

* @param layoutId

*/

public static void initContentView(Context context, int layoutId) {

mInflater = LayoutInflater.from(context);

mContentView = mInflater.inflate(layoutId, null, false);

if (mInflater == null || mContentView == null) {

throw new RuntimeException(

"ViewFinder init failed, mInflater == null || mContentView == null.");

}

}

public static View getContentView() {

return mContentView;

}

public static T findViewById(int viewId) {

// 先从view map中查找,如果有的缓存的话直接使用,否则再从mContentView中找

View tagetView = mViewMap.get(viewId);

if (tagetView == null) {

tagetView = mContentView.findViewById(viewId);

mViewMap.put(viewId, tagetView);

}

return tagetView == null ? null : (T) mContentView.findViewById(viewId);

}

}

3.ViewFinder类的使用

首先调用initContentView方法,将Context和布局id传进来,再调用ViewFinder.findViewById();方法获得对象。

@Override

protected void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.activity_main);

// 初始化

ViewFinder.initContentView(this, R.layout.activity_main) ;

// 查找子控件

TextView textView = ViewFinder.findViewById(R.id.my_textview);

ImageView imageView = ViewFinder.findViewById(R.id.my_imageview);

ListView listView = ViewFinder.findViewById(R.id.my_listview);

}

4.参考资料:

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值