是这样的,我做了一个实现ViewPager的程序,包含两个View页面;
我在其中一个View页面中添加了Button按钮,然后在MainActivity里面写Button点击
事件的时候总是没有响应,然后在网上查了一下说应该在PagerAdapter的instantiateItem方法里面实例化Button然后写响应事件,下面是我的代码:
public Object instantiateItem(ViewGroup container, int position) {
switch (position) {
case 1:
musicName = (EditText) theList.get(position).findViewById(
R.id.musicname_edittext);
singerName = (EditText) theList.get(position).findViewById(
R.id.singername_edittext);
Button searchButton = (Button) theList.get(position).findViewById(
R.id.search_button);
Button resetButton = (Button) theList.get(position).findViewById(
R.id.reset_button);
// 搜索按钮点击事件
searchButton.setOnClickListener(new OnClickListener() {
// 通过用户输入的歌名和歌手名获取url,通过url获取xml文件输入流,然后sax解析xml输入流
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
String urlString = getUrl();
GetInputStreamAsyncTask getInputTask = new GetInputStreamAsyncTask();
getInputTask.execute(urlString);
inputStream = getInputTask.getInputStream();
saxParseXML(inputStream);
}
});
// 重置按钮点击事件
resetButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
musicName.setText("");
singerName.setText("");
}
});
break;
default:
break;
}
container.addView(theList.get(position), 0);
return theList.get(position);
}
我在一个Button响应事件中想使用AsyncTask获取网络上一个xml文件的InputStream,然后用sax解析这个InputStream,下面是我的AsycTask类的代码:
```public class GetInputStreamAsyncTask extends AsyncTask{
private InputStream inputStream;
public GetInputStreamAsyncTask(){
}
public InputStream getInputStream() {
return inputStream;
}
@Override
protected Boolean doInBackground(String... params) {
// TODO Auto-generated method stub
DownloadDataByUrl dl=new DownloadDataByUrl();
try {
inputStream=dl.getInputStreamFromUrl(params[0]);
byte[] b = new byte[1024];
StringBuilder sb = new StringBuilder();
int len = -1;
try {
while ((len = inputStream.read(b)) != -1) {
sb.append(new String(b, 0, len));
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("xiaoqiang:" + sb);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
}
可以看到我在doInBackGround方法里面获取InputStream后进行了输出操作,而且运行程序后输出了完整的xml文件字符,如下:
![图片说明](https://img-ask.csdn.net/upload/201507/20/1437407420_269505.png)
这个是logcat的错误信息,我在 getInputTask.execute(urlString); 语句后面调用了System.out.println()输出语句成功。但是在saxParseXML(inputStream);语句之前调用System.out.println()输出语句失败。
![图片说明](https://img-ask.csdn.net/upload/201507/20/1437407573_37315.png)
调试了一整天也没有找出问题所在,求解~~