读书人

android中LayoutInflater的运用(转)

发布时间: 2012-07-16 15:44:59 作者: rapoo

android中LayoutInflater的使用(转)

?Inflater英文意思是膨胀,在Android中应该是扩展的意思吧。?
LayoutInflater的作用类似于 findViewById(),不同点是LayoutInflater是用来找layout文件夹下的xml布局文件,并且实例化!而 findViewById()是找具体某一个xml下的具体 widget控件(如:Button,TextView等)。

???(0)她可以有很多地方可以使用,如BaseAdapter的getView中,自定义Dialog中取得view中的组件widget等等。
它的用法有2种:

复制到剪贴板??Java代码
  1. Java代码?? //基本用法????
  2. public?void?showCustomDialog(){???? ??AlertDialog.Builder?builder;????
  3. ??AlertDialog?alertDialog;???? ??Context?mContext?=?AppActivity.this;????
  4. //下面俩种方法都可以???? ??//LayoutInflater?inflater?=?getLayoutInflater();????
  5. ??LayoutInflater?inflater?=?(LayoutInflater)????? mContext.getSystemService(LAYOUT_INFLATER_SERVICE);????
  6. ??View?layout?=?inflater.inflate(R.layout.custom_dialog,null);???? ??TextView?text?=?(TextView)?layout.findViewById(R.id.text);????
  7. ??text.setText("Hello,?Welcome?to?Mr?Wei's?blog!");???? ??ImageView?image?=?(ImageView)?layout.findViewById(R.id.image);????
  8. ??image.setImageResource(R.drawable.icon);???? ??builder?=?new?AlertDialog.Builder(mContext);????
  9. ??builder.setView(layout);???? ??alertDialog?=?builder.create();????
  10. ??alertDialog.show();???? ?}????
  11. }???? ????
  12. protected?void?showToast(int?type)?{?????? ????????Toast.makeText(this,?"*********",?Toast.LENGTH_LONG).show();??????
  13. ?????? ????????LayoutInflater?li?=?(LayoutInflater)?getSystemService(Context.LAYOUT_INFLATER_SERVICE);??????
  14. ????????View?view?=?li.inflate(R.layout.toast,?null);?????? ??????????????
  15. ????????Toast?toast?=?new?Toast(this);?????? ????????toast.setView(view);??????
  16. ????????toast.setDuration(type);?????? ????????toast.show();??????
  17. ????}?????

读书人网 >Android

热点推荐