怎样动态修改listview动态更新数据中Item的数据

如何实现可动态调整隐藏header的listview
需求:根据某种需要,可能需要动态调整listview的页眉页脚,譬如将header作为显示板使用。
难点:listView.addHeaderView()方法必须在setAdapter()方法前调用,否则就会抛异常。至于为什么会抛异常,查看下ListView的源代码即可发现。因此,在设置HeaderView之后又想将headerView移除或者隐藏,则需要绕很大的弯子:将adapter保存起来-移除headerView-(或者更换headerview)-再将adapter设置上去。
隐藏headerview思路:使用View.GONE属性进行隐藏
尝试1.itemView结构如下:
&&&LinearLayout&android:id="@+id/item_root"
android:layout_width="fill_parent"
android:layout_height="50dip"
android:orientation="vertical" &
&TextView& android:id="@+id/tv_1"&/&
&TextView&&android:id="@+id/tv_2"&/&
&/LinearLayout
此时,有如下逻辑:
& ListView
listView =
listView.addHearderView(item_root);
listView.setAdapter(adapter);
adapter.add(xxxxx);添加数据
item_root.setVisibility(View.GONE);
按道理,最后一句应该可以起到隐藏headerView的目的,但实际效果(魅族MX上测试发现),item_root的地方的确没有控件了,但item_root占用的50dip高度还在,即原来headerView的地方变成了一片空白区域!和View.INVISIBILE效果一样了,汗死!
&继续尝试如下,修改itemView的结构:
&LinearLayout&android:id="@+id/item_root"
& android:layout_width="fill_parent"
& android:layout_height="50dip"
& android:orientation="vertical"
&&LinearLayout&android:id="@+id/item_container"
&TextView&&android:id="@+id/tv_1"&/&
&TextView&&android:id="@+id/tv_2"&/&
&&/LinearLayout&
&/LinearLayout
&此结构较之前的结构增加了一个多余的Layout(item_container)来囊括item内部控件。此时,如果在item_container&.setVisibility(View.GONE)则可以完美实现隐藏HeaderView的目的!
结论:View.GONE属性貌似不作用在根Layout上。
新的问题:
如果在item_root上使用了Shape背景,且此背景存在MinSize,那么此方法又失效了。。。
规避处理:如果的确必须要在HeaderView上添加背景background的话,那么请将background设置在item_container上吧,不要设置在item_root上,如此就可以规避新的问题了。
已投稿到:
以上网友发言只代表其个人观点,不代表新浪网的观点或立场。所有回答(2)
代码太短,看不出来是不是同一个listData。ListView的数据源只能使用同一个对象,因为找数据是按引用来读的,一旦重新赋值,引用就会改变。所以先要确认listData是同一个。
是当时写错了,后来自己找到了原因
&&&您需要以后才能回答,未注册用户请先。--旗下,中国最好的系统开发学习平台!
热门推荐:
当前位置: >
从网络读取数据并动态的显示在ListView中
发布时间: 13:38 | 作者:采集侠 | 来源:网络整理 | 浏览:
这两天写了个小程序,使用了从网络读取xml数据,并显示在ListView中。
这里面有几个关键点:
从网络读取数据
SAX解析xml
异步填充ListView
先看下截图:
非常简单的界面哈
为了方便,我再自己的服务器上,放了一个xml文件,其内容主要是:
&?xml version="1.0"?&&
&products&&
&product&&
&price&100&/price&&
&name&android dev&/name&&
&image src="image/android1.png"/&&
&/product&&
&product&&
&price&100&/price&&
&name&androiddev2&/name&&
&image src="image/android1.png"/&&
&/product&&
&!-- 接着重复下去.... --&&
&/products&&
该程序,首先用一个AsyncTask新启一个线程,来下载和解析xml;和主线程通过Handler对象来通讯。
下载XML文件
通过HTTPGet来下载xml。这时apache提供的包,需要首先包含如下包:
import org.apache.http.HttpE&
import org.apache.http.HttpR&
import org.apache.http.HttpS&
import org.apache.http.client.HttpC&
import org.apache.http.client.methods.HttpG&
import org.apache.http.impl.client.DefaultHttpC&
代码如下:(使用Get方法)
protected String doInBackground(String... params) {&
HttpGet httpRequest = new HttpGet(params[0]); //从url 创建一个HttpGet对象&
HttpClient httpclient = new DefaultHttpClient();&
//mShowHtml.setText("");&
HttpResponse httpResponse = httpclient.execute(httpRequest);&
if(httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK){//获取http的返回值代码&
HttpEntity entitiy = httpResponse.getEntity();&
InputStream in = entitiy.getContent();//获得内容&
//解析xml,下面详述&
InputSource source = new InputSource(in);&
SAXParserFactory sax = SAXParserFactory.newInstance();&
XMLReader xmlReader = sax.newSAXParser().getXMLReader();&
xmlReader.setContentHandler(new ProductHandler());&
xmlReader.parse(source);&
//return "请求失败!";&
//mShowHtml.setText("请求失败");&
//Message mymsg = mMainHandler.obtainMessage();&
//mymsg.obj = "请求失败";&
//mMainHandler.sendMessage(mymsg);&
}catch(IOException e){&
e.printStackTrace();&
}catch(SAXException e) {&
e.printStackTrace();&
}catch(ParserConfigurationException e) {&
e.printStackTrace();&
使用SAX的解析方法,先包含必须得包
import org.xml.sax.InputS&
import org.xml.sax.SAXE&
import org.xml.sax.XMLR&
import org.xml.sax.helpers.DefaultH&
解析的代码,正如上面所示:
//InputSource是解析源,可以通过一个InputStream创建&
urce source = new InputSource(in);&&&&&&&&&&&&&&&&&&&
SAXParserFactory sax = SAXParserFactory.newInstance();&
der xmlReader = sax.newSAXParser().getXMLReader();&&&&&&&&&&&&&&&&&&&&&&&&&&&&
xmlReader.setContentHandler(new ProductHandler());//ProductHandler是解析的句柄&&&&&&&&&&&&&&&&&&&&&&&&&
der.parse(source);&
SAX主要使用ContentHandler接口来传递解析好得数据,不过,更经常使用的是DefaultHandler
class ProductHandler extends DefaultHandler { //从DefaultHandler继承即可&
private ProductInfo curP&
private S&
//解析到一个标签时调用&
public void startElement(String uri, String localName, String name, org.xml.sax.Attributes attributes) throws SAXException {&
if(localName.equals("product")) {//遇到product标签,进行解析&
curProduct = new ProductInfo();&
else if(localName.equals("image")) {&
//set name&
curProduct.image = attributes.getValue("src");//提取image src属性&
super.startElement(uri, localName, name, attributes);&
public void endElement(String uri, String localName, String name) throws SAXException{&
if(localName.equals("product")) {//当解析到一个标签结束时,发送一个消息,把Product类作为参数传递&
//send event&
//get main handler&
Message msg = mMainHandler.obtainMessage();&
msg.obj = curP&
mMainHandler.sendMessage(msg);&
//Log.i("Product:", curProduct.toString());&
else if(localName.equals("name")) {&
//set name&
curProduct.name =//保存名字&
else if(localName.equals("price")) {&
curProduct.price = Float.parseFloat(content);&span&//保存价格&/span&&
super.endElement(uri, localName, name);&
//这里获取具体的内容,是标签下保存的文本&
public void characters (char[] ch, int start, int length)& throws SAXException&
content = new String(ch, start, length);&
//Log.i("Parser:" ,content);&
super.characters(ch, start, length);&
ProductInfo类的定义非常简单
class ProductInfo {&
public String toString() {&
return "\nName:" + name +"\nPrice :" + price + "\nImage:" +&
在AsyncTask中执行以上代码
public class GetHttpTask extends AsyncTask&String, Integer, String& {&
public GetHttpTask() {&
protected void onPreExecute() { //在进入线程之前执行。该函数在调用者线程内执行&
protected String doInBackground(String... params) {//线程的执行主体&
HttpGet httpRequest = new HttpGet(params[0]);&
.................. //主要执行下载和解析的嗲吗&
protected void onPostExecute(String result) {//完成后调用&
在主线程中,调用GetHttpTask的execute方法就可以执行
btn.setOnClickListener(new View.OnClickListener() {//在onCreate函数中调用&
@Override&
public void onClick(View v) {&
// TODO Auto-generated method stub&
httpGet();&
httpGet方法:
void httpGet() {&
GetHttpTask task = new GetHttpTask();&
task.execute("http://192.168.1.111:8080/nfcdemo/products.xml");&
异步传递消息
上面的例子中,在endElement函数中,发送了消息,下面是接收消息
在主Activity中,声明了一个Handler mHandler对象,并在onCreate时,这样做
mMainHandler = new Handler() {&
public& void handleMessage(Message msg) {&
//mShowHtml.append((String)msg.obj);&
if(msg.obj != null) {&
ProductInfo prod = (ProductInfo)msg.&
Log.i("Prodcut:", prod.toString());&
//mShowHtml.append(prod.toString());&
HashMap&String, Object& map = new HashMap&String, Object&();&
map.put("name", prod.name);&
map.put("price", "RMB" + prod.price);&
mlist.add(map); //mlist保存了列表的具体数据&
mProdList.notifyDataSetChanged();//mProdList是一个ListView对象,该函数引起ListView重读数据&
这个过程的要点基本如上,贴上所有代码吧!关于ListView的用法,可以参考
package com.test.&
import java.io.IOE&
import java.io.InputS&
import java.util.ArrayL&
import java.util.HashM&
import javax.xml.parsers.ParserConfigurationE&
import javax.xml.parsers.SAXParserF&
import org.apache.http.HttpE&
import org.apache.http.HttpR&
import org.apache.http.HttpS&
import org.apache.http.client.HttpC&
import org.apache.http.client.methods.HttpG&
import org.apache.http.impl.client.DefaultHttpC&
import org.xml.sax.InputS&
import org.xml.sax.SAXE&
import org.xml.sax.XMLR&
import org.xml.sax.helpers.DefaultH&
import android.app.A&
import android.os.AsyncT&
import android.os.B&
import android.os.H&
import android.os.M&
import android.util.L&
import android.view.V&
import android.widget.B&
import android.widget.EditT&
import android.widget.ListV&
import android.widget.SimpleA&
public class HtmltestActivity extends Activity {&
EditText mUrlT&
//EditText mShowH&
ListView mP&
Handler mMainH&
SimpleAdapter mProdL&
ArrayList&HashMap&String,Object&&&
/** Called when the activity is first created. */&
@Override&
public void onCreate(Bundle savedInstanceState) {&
super.onCreate(savedInstanceState);&
setContentView(R.layout.main);&
mUrlText = (EditText)findViewById(R.id.eturl);&
//mShowHtml = (EditText)findViewById(R.id.etshowhtml);&
mProducts = (ListView)findViewById(R.id.productList);&
Button btn = (Button)findViewById(R.id.btngo);&
mlist = new ArrayList&HashMap&String, Object&&();&
mProdList = new SimpleAdapter(this,&
R.layout.listitem,&
new String[]{"name", "price"},&
new int[]{R.id.prd_title, R.id.prd_price}&
mProducts.setAdapter(mProdList);&
btn.setOnClickListener(new View.OnClickListener() {&
@Override&
public void onClick(View v) {&
// TODO Auto-generated method stub&
httpGet();&
mMainHandler = new Handler() {&
public& void handleMessage(Message msg) {&
//mShowHtml.append((String)msg.obj);&
if(msg.obj != null) {&
ProductInfo prod = (ProductInfo)msg.&
Log.i("Prodcut:", prod.toString());&
//mShowHtml.append(prod.toString());&
HashMap&String, Object& map = new HashMap&String, Object&();&
map.put("name", prod.name);&
map.put("price", "RMB" + prod.price);&
mlist.add(map);&
mProdList.notifyDataSetChanged();&
void httpGet() {&
GetHttpTask task = new GetHttpTask();&
task.execute("http://192.168.1.111:8080/nfcdemo/products.xml");&
public class GetHttpTask extends AsyncTask&String, Integer, String& {&
public GetHttpTask() {&
protected void onPreExecute() {&
protected String doInBackground(String... params) {&
HttpGet httpRequest = new HttpGet(params[0]);&
HttpClient httpclient = new DefaultHttpClient();&
//mShowHtml.setText("");&
HttpResponse httpResponse = httpclient.execute(httpRequest);&
if(httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK){&
HttpEntity entitiy = httpResponse.getEntity();&
InputStream in = entitiy.getContent();&
InputSource source = new InputSource(in);&
SAXParserFactory sax = SAXParserFactory.newInstance();&
XMLReader xmlReader = sax.newSAXParser().getXMLReader();&
xmlReader.setContentHandler(new ProductHandler());&
xmlReader.parse(source);&
//return "请求失败!";&
//mShowHtml.setText("请求失败");&
//Message mymsg = mMainHandler.obtainMessage();&
//mymsg.obj = "请求失败";&
//mMainHandler.sendMessage(mymsg);&
}catch(IOException e){&
e.printStackTrace();&
}catch(SAXException e) {&
e.printStackTrace();&
}catch(ParserConfigurationException e) {&
e.printStackTrace();&
protected void onPostExecute(String result) {&
//mShowHtml.setText(result);&
class ProductInfo {&
public String toString() {&
return "\nName:" + name +"\nPrice :" + price + "\nImage:" +&
class ProductHandler extends DefaultHandler {&
private ProductInfo curP&
private S&
public void startElement(String uri, String localName, String name, org.xml.sax.Attributes attributes) throws SAXException {&
if(localName.equals("product")) {&
curProduct = new ProductInfo();&
else if(localName.equals("image")) {&
//set name&
curProduct.image = attributes.getValue("src");&
super.startElement(uri, localName, name, attributes);&
public void endElement(String uri, String localName, String name) throws SAXException{ &
if(localName.equals("product")) {&
//send event&
//get main handler&
Message msg = mMainHandler.obtainMessage();&
msg.obj = curP&
mMainHandler.sendMessage(msg);&
//Log.i("Product:", curProduct.toString());&
else if(localName.equals("name")) {&
//set name&
curProduct.name =&
else if(localName.equals("price")) {&
curProduct.price = Float.parseFloat(content);&
super.endElement(uri, localName, name);&
public void characters (char[] ch, int start, int length)& throws SAXException&
content = new String(ch, start, length);&
//Log.i("Parser:" ,content);&
super.characters(ch, start, length);&
&?xml version="1.0" encoding="utf-8"?&&
&LinearLayout xmlns:android="/apk/res/android"&
android:layout_width="fill_parent"&
android:layout_height="fill_parent"&
android:orientation="vertical" &&
&LinearLayout&
android:id="@+id/linearLayout1"&
android:layout_width="match_parent"&
android:layout_height="wrap_content" &&
&EditText&
android:id="@+id/eturl"&
android:layout_width="match_parent"&
android:layout_height="wrap_content"&
android:layout_weight="1" &&
&requestFocus /&&
&/EditText&&
android:id="@+id/btngo"&
android:layout_width="100dp"&
android:layout_height="wrap_content"&
android:layout_weight="1"&
android:text="Go!" /&&
&/LinearLayout&&
&ListView&
android:id="@+id/productList"&
android:layout_width="match_parent"&
android:layout_height="match_parent" &&
&/ListView&&
&/LinearLayout&&
listitem.xml
&?xml version="1.0" encoding="utf-8"?&&
&RelativeLayout xmlns:android="/apk/res/android"&
android:layout_width="match_parent"&
android:layout_height="match_parent" &&
&ImageView&
android:id="@+id/product_icon"&
android:layout_width="wrap_content"&
android:layout_height="wrap_content"&
android:layout_alignParentLeft="true"&
android:layout_alignParentTop="true"&
android:src="@drawable/ic_launcher" /&&
&TextView&
android:id="@+id/prd_title"&
android:layout_width="wrap_content"&
android:layout_height="wrap_content"&
android:layout_alignParentTop="true"&
android:layout_toRightOf="@+id/product_icon"&
android:text="TextView" /&&
&TextView&
android:id="@+id/prd_price"&
android:layout_width="wrap_content"&
android:layout_height="wrap_content"&
android:layout_alignParentRight="true"&
android:layout_alignParentTop="true"&
android:text="TextView" /&&
&/RelativeLayout&& &Android怎么在listview中的item动态添加控件。比如我不清楚究竟有几张图片需要解析数据后才知道_百度知道
Android怎么在listview中的item动态添加控件。比如我不清楚究竟有几张图片需要解析数据后才知道
提问者采纳
viewholder, 在getview自定义adapter, 每个item里面有个空的LinearLayout,
每次获取到viewholder后,如,解析过来的数据; 之后根据,LinearLayout,往linearlayout.linearlayout.removeAllViews(), getView里面动态加载布局,先得确认你的图片是怎么摆放的
提问者评价
其他类似问题
为您推荐:
android的相关知识
其他1条回答
建议代码布局。
等待您来回答
下载知道APP
随时随地咨询
出门在外也不愁}

我要回帖

更多关于 c listviewitem 修改 的文章

更多推荐

版权声明:文章内容来源于网络,版权归原作者所有,如有侵权请点击这里与我们联系,我们将及时删除。

点击添加站长微信