---
title: "setContentview后，单击事件不可用的解决方法"
author: "ictch"
date: "2011-06-14T13:23:06Z"
tags: []
categories: ["移动开发"]
slug: "setcontentview"
draft: false
lastmod: "2011-06-14T13:23:06Z"
id: 1086364
url: "https://ictch.iteye.com/blog/1086364"
---

今天做一个小程序时，中间界面的切换全部用了setContentview（int  id） 这个方法来实现。 然后，当我的有个需求就是需要点击返回按钮，返回到上层菜单时，发现setContentview之后，所有Button的监听器似乎都失灵了。

查了一些资料，发现自己对于setContentview这个方法自己没有理解好， 原来一直都是使用这个setContentview（int  id） 来切换界面，但是这一次我的Activy生成之后， 如果仅仅setContentview（int  id），那么View需要重新绘制，上面的Button也就不存在了原来注册的监听器。 熟悉setContentview这个方法的朋友都知道，这个方法还有一个重载方法  
setContentview（View  v），传递view参数，就可以实现界面切换时， 同时重绘了VIEW

具体实现：  
  LayoutInflater inflater = getLayoutInflater();  
 View layout = inflater.inflate(R.layout.myxml,null);  
上篇博客中提到了这个LayoutInflater ，这个类简单来说是查找layout文件夹下面的xml文件，功能类似的有findViewByid（查找xml文件里的控件），然后通过第二句代码生成一个View对象  
接着，我们就可以setContentview（layout ）来实现切换界面了，这样一来，我们那个layout 里面的控件的单击事件就还是可以使用啦。