Android的onItemClicklistener在列表视图不工作 [英] Android onItemClicklistener in listview not working

查看:135
本文介绍了Android的onItemClicklistener在列表视图不工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

谁能帮助我与我的问题。我有一个TabActivity每个选项卡上的触摸打开它在这个时候我得到我想要通过使用OnItemClickListener使点击所需物品的清单扩展ListActivity一个新的活动。

我正在附加我的的main.xml 请通过它,让我知道,如果有需要的任何修改

 < XML版本=1.0编码=UTF-8&GT?;
< LinearLayout中的xmlns:机器人=htt​​p://schemas.android.com/apk/res/android
    机器人:方向=垂直
    机器人:layout_width =FILL_PARENT
    机器人:layout_height =FILL_PARENT>
    < TabHost
        机器人:ID =@机器人:ID / tabhost
        机器人:layout_width =FILL_PARENT
        机器人:layout_height =FILL_PARENT>
        <的LinearLayout
            机器人:方向=垂直
            机器人:layout_width =FILL_PARENT
            机器人:layout_height =FILL_PARENT
            机器人:填充=5DP>
            < TabWidget
                机器人:ID =@机器人:ID /标签
                机器人:layout_width =FILL_PARENT
                机器人:layout_height =WRAP_CONTENT/>
            <的FrameLayout
                机器人:ID =@机器人:ID / tabcontent
                机器人:layout_width =FILL_PARENT
                机器人:layout_height =FILL_PARENT
                机器人:填充=5DP/>
            <的TextView
                机器人:ID =@ + ID / ITEM_TITLE
                机器人:layout_width =FILL_PARENT
                机器人:layout_height =WRAP_CONTENT
                机器人:textAppearance =机器人:ATTR / textAppearanceMedium
                机器人:填充=2DP
                机器人:TEXTSIZE =20dp/>
            <的TextView
                机器人:ID =@ + ID / item_subtitle
                机器人:layout_width =FILL_PARENT
                机器人:layout_height =WRAP_CONTENT
                机器人:填充=2DP
                机器人:TEXTSIZE =13dp/>
        < / LinearLayout中>
    < / TabHost>
< / LinearLayout中>
 

活动

 公共类TopNewsActivity扩展ListActivity
{

    / **第一次创建活动时调用。 * /
    @覆盖
    公共无效的onCreate(包savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        的setContentView(R.layout.listplaceholder);

        ArrayList的< HashMap的<字符串,字符串>> mylist中=新的ArrayList< HashMap的<字符串,字符串>>();

        XML字符串= XMLfunctions.getTopNewsXML();
        文档DOC = XMLfunctions.XMLfromString(XML);

        INT numResults = XMLfunctions.numResults(DOC);

        如果((numResults&所述; = 0))
        {
            Toast.makeText(TopNewsActivity.this,没有个结果发现,Toast.LENGTH_LONG).show();
            完();
        }

        节点列表节点= doc.getElementsByTagName(结果);

    的for(int i = 0; I< nodes.getLength();我++){
        HashMap的<字符串,字符串>图=新的HashMap<字符串,字符串>();

        元素e =(元)nodes.item(我);
        map.put(ID,XMLfunctions.getValue(即,ID));
        map.put(名,纳摩:+ XMLfunctions.getValue(即名));
        map.put(分数,分数:+ XMLfunctions.getValue(即分数));
        mylist.add(图)
    }

    ListAdapter适配器=新SimpleAdapter(这一点,mylist中,R.layout.main,
                    新的String [] {姓名,分数},
                    新的INT [] {R.id.item_title,R.id.item_subtitle});

    setListAdapter(适配器);

        最终的ListView LV = getListView();
        /*lv.setOnItemClickListener(new OnItemClickListener(){
            @覆盖
            公共无效onItemClick(适配器视图<>母公司视图中查看,INT位置,长的id){
                @燮pressWarnings(未登记)
                HashMap的<字符串,字符串> O =(HashMap的<字符串,字符串>)lv.getOnItemClickListener();

                意图I =新的意图(view.getContext(),NewsDetails.class);
                i.putExtra(CONTENT_ID,o.get(ID));
                i.putExtra(标题,o.get(标题));
                startActivity(ⅰ);
                lv.setOnItemClickListener(本);

            }
        }); * /

        最后OnItemClickListener myClickListener =新OnItemClickListener()
        {
            @覆盖
            公共无效onItemClick(适配器视图<>一种,视图中查看,INT位置,长ID)
            {
                @燮pressWarnings(未登记)
                HashMap的<字符串,字符串> O =(HashMap的<字符串,字符串>)lv.getOnItemClickListener();

                意图I =新的意图(view.getContext(),NewsDetails.class);
                i.putExtra(CONTENT_ID,o.get(ID));
                i.putExtra(标题,o.get(NAAM));
                startActivity(ⅰ);
            }
        };
        lv.setOnItemClickListener(myClickListener);
    }
}
 

TabActivity

 公共类InfralineTabWidget扩展TabActivity {

公共无效的onCreate(包savedInstanceState){
    super.onCreate(savedInstanceState);
    的setContentView(R.layout.main);

    资源RES = getResources(); //资源对象获取可绘
    TabHost tabHost =(TabHost)getTabHost(); //活动TabHost
    TabHost.TabSpec规范; // Resusable则tabspec为每个标签
    意向意图; //可重复使用意向为每个标签

    //创建一个Intent来启动一个活动的标签(重复使用)
    意图=新的意图()setClass(这一点,TopNewsActivity.class)。

    //初始化则tabspec为每个标签,并把它添加到TabHost
    规格= tabHost.newTabSpec(的TopNews)setIndicator(最新新闻,res.getDrawable(R.drawable.tab_news))setContent(意向)。
    tabHost.addTab(规范);

    //执行相同的其他标签
    意图=新的意图()setClass(这一点,PowerActivity.class)。
    规格= tabHost.newTabSpec(权力)setIndicator(电源,res.getDrawable(R.drawable.tab_power))setContent(意向)。
    tabHost.addTab(规范);

    tabHost.setCurrentTab(0);

}

 }
 

ListPlaceHolder.xml

 < XML版本=1.0编码=UTF-8&GT?;

< LinearLayout中的xmlns:机器人=htt​​p://schemas.android.com/apk/res/android

机器人:方向=垂直

机器人:layout_width =FILL_PARENT

机器人:layout_height =FILL_PARENT>

<的ListView
    机器人:ID =@ ID / Android的:清单
    机器人:layout_width =FILL_PARENT
    机器人:layout_height =WRAP_CONTENT
    机器人:layout_weight =1
    机器人:drawSelectorOnTop =FALSE/>

  <的TextView
    机器人:ID =@ ID /安卓:空
    机器人:layout_width =FILL_PARENT
    机器人:layout_height =WRAP_CONTENT
    机器人:文本=无数据/>
 < / LinearLayout中>
 

XMLFunction.java

 包com.infra.android.views;

 进口java.io.BufferedReader中;
 进口java.io.FileReader;
 进口java.io.IOException异常;
 进口java.io.StringReader中;
 进口java.io.UnsupportedEncodingException;
 进口java.net.MalformedURLException;
 进口java.text.CharacterIterator中;
 进口java.text.StringCharacterIterator的;

进口javax.xml.parsers.DocumentBuilder中;
进口javax.xml.parsers.DocumentBuilderFactory中;
进口javax.xml.parsers.ParserConfigurationException;

进口org.apache.http.HttpEntity;
  进口org.apache.http.Htt presponse;
 进口org.apache.http.client.methods.HttpPost;
进口org.apache.http.impl.client.DefaultHttpClient;
进口org.apache.http.util.EntityUtils;
进口org.jsoup.Jsoup;
进口org.w3c.dom.CharacterData中的;
进口org.w3c.dom.Document中;
进口org.w3c.dom.Element中;
进口org.w3c.dom.Node中;
进口org.w3c.dom.NodeList;
进口org.xml.sax.InputSource中;
进口org.xml.sax.SAXException;

公共类XMLfunctions {

公共最后静态文件XMLfromString(XML字符串){

    文档DOC = NULL;

    DocumentBuilderFactory的DBF = DocumentBuilderFactory.newInstance();
    尝试 {

        DocumentBuilder的DB = dbf.newDocumentBuilder();

        InputSource的是=新的InputSource();
        is.setCharacterStream(新StringReader(XML));
        DOC = db.parse(是);

    }赶上(的ParserConfigurationException E){
        的System.out.println(XML解析错误:+ e.getMessage());
        返回null;
    }赶上(的SAXException E){
        的System.out.println(错的XML文件的结构:+ e.getMessage());
        返回null;
    }赶上(IOException异常E){
        的System.out.println(I / O exeption:+ e.getMessage());
        返回null;
    }

    返回文档;

}


/ **返回元素值
  *参数ELEM元素(这是XML标记)
  返回:元素的值,否则空字符串
  * /
 公共最后静态字符串getElementValue(节点ELEM){
     节点的孩子;
     如果(ELEM!= NULL){
         如果(elem.hasChildNodes()){
             对于(孩子= elem.getFirstChild();!小子= NULL;孩子= kid.getNextSibling()){
                 如果(kid.getNodeType()== Node.TEXT_NODE){
                     返回kid.getNodeValue();
                 }
             }
         }
     }
     返回 ;
 }

 / *开始解析热门新闻XML * /
 公共静态字符串getTopNewsXML(){
        串线= NULL;

        尝试 {

            DefaultHttpClient的HttpClient =新DefaultHttpClient();
            HttpPost httpPost =新HttpPost(http://p-xr.com/xml);

            HTT presponse HTT presponse = httpClient.execute(httpPost);
            HttpEntity httpEntity = HTT presponse.getEntity();
            行= EntityUtils.toString(httpEntity);

        }赶上(UnsupportedEncodingException E){
            行=<结果状态= \错误\><味精>无法连接到服务器16; /味精>< /结果>;
        }赶上(MalformedURLException异常E){
            行=<结果状态= \错误\><味精>无法连接到服务器16; /味精>< /结果>;
        }赶上(IOException异常E){
            行=<结果状态= \错误\><味精>无法连接到服务器16; /味精>< /结果>;
        }

        回线;

}


公共静态INT numResults(DOC文件){
    节点的结果= doc.getDocumentElement();
    INT RES = -1;

    尝试{
        RES = Integer.valueOf(results.getAttributes()getNamedItem(计数)getNodeValue());
    }赶上(例外五){
        RES = -1;
    }

    返回水库;
}

公共静态字符串的getValue(元素项,字符串str){
    节点列表N = item.getElementsByTagName(STR);
    返回XMLfunctions.getElementValue(n.item(0));
}

   }
 

解决方案

您必须让 ClassCastException异常,如果没有,至少 NullPointerException异常:

 的HashMap<字符串,字符串> O =(HashMap的<字符串,字符串>)lv.getOnItemClickListener();
 

您应该将其更改为

 的HashMap<字符串,字符串> O =(HashMap的<字符串,字符串>)adapter.getItem(位置);
 

如果您试图访问列表项渲染器的基本对象。

修改

我刚刚尝试了这个应用程序,和它的作品在我结束(以虚拟数据,类等)
我所虽然改变了,是

 最后ListAdapter适配器=新SimpleAdapter(这一点,mylist中,R.layout.main,
        新的String [] {称号},新的INT [] {R.id.item_title});
setListAdapter(适配器);

getListView()。setOnItemClickListener(新OnItemClickListener()
{
    @覆盖
    公共无效onItemClick(适配器视图<>一种,视图中查看,INT位置,长ID)
    {
        HashMap的<字符串,字符串> O =(HashMap的<字符串,字符串>)adapter.getItem(位置);

        意图I =新的意图(TopNewsActivity.this,NewsDetails.class);
        i.putExtra(CONTENT_ID,o.get(ID));
        i.putExtra(标题,o.get(标题));
        startActivity(ⅰ);
    }
});
 

编辑2

新手的错误注重症状,我们相信这个问题是存在的......不是说没有了,笔记上面都站着。

但采取上述共享类和布局,只有当,我才明白,你实际上使用 TabView的的布局作为itemRenderer的用于内部列表中选择 TabView的 ...

这是的main.xml 不应该包含这两个 TextViews ,他们应该在一个单独的XML文件(说: list_item.xml ):

 < XML版本=1.0编码=UTF-8&GT?;
< LinearLayout中的xmlns:机器人=htt​​p://schemas.android.com/apk/res/android
    机器人:方向=垂直机器人:layout_width =FILL_PARENT
    机器人:layout_height =WRAP_CONTENT>
    < TextView的机器人:ID =@ + ID / ITEM_TITLE机器人:layout_width =FILL_PARENT
        机器人:layout_height =WRAP_CONTENT机器人:textAppearance =机器人:ATTR / textAppearanceMedium
        机器人:填充=2DP机器人:TEXTSIZE =20dp/>
    < TextView的机器人:ID =@ + ID / item_subtitle
        机器人:layout_width =FILL_PARENT机器人:layout_height =WRAP_CONTENT
        机器人:填充=2DP机器人:TEXTSIZE =13dp/>
< / LinearLayout中>
 

和您的 的main.xml 应为

 < XML版本=1.0编码=UTF-8&GT?;
< LinearLayout中的xmlns:机器人=htt​​p://schemas.android.com/apk/res/android
    机器人:方向=垂直
    机器人:layout_width =FILL_PARENT
    机器人:layout_height =FILL_PARENT>
    < TabHost
        机器人:ID =@机器人:ID / tabhost
        机器人:layout_width =FILL_PARENT
        机器人:layout_height =FILL_PARENT>
        <的LinearLayout
            机器人:方向=垂直
            机器人:layout_width =FILL_PARENT
            机器人:layout_height =FILL_PARENT
            机器人:填充=5DP>
            < TabWidget
                机器人:ID =@机器人:ID /标签
                机器人:layout_width =FILL_PARENT
                机器人:layout_height =WRAP_CONTENT/>
            <的FrameLayout
                机器人:ID =@机器人:ID / tabcontent
                机器人:layout_width =FILL_PARENT
                机器人:layout_height =FILL_PARENT
                机器人:填充=5DP/>
        < / LinearLayout中>
    < / TabHost>
< / LinearLayout中>
 

最后,当你初始化列表适配器,您应该将其更改为使用该 list_item.xml

 最后ListAdapter适配器=
    新SimpleAdapter(这一点,mylist中,R.layout.list_item,新的String []
        {姓名,分数},新的INT [] {R.id.item_title,R.id.item_subtitle});
 

,就是这样。

现在它的工作原理,并没有一个全新的 TabView的(不带任何选项卡)中的每个列表项,既没有多余的,无用的,无形的 TextViews 在主布局。

Can anyone help me out with my problem. I have a TabActivity each tab is on touch opens a new activity which extends ListActivity at this time i get the list of desired items which i want to make clickable by using OnItemClickListener.

i'm attaching my main.xml please go through it and let me know if there are any changes required

  <?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent">
    <TabHost
        android:id="@android:id/tabhost"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent">
        <LinearLayout
            android:orientation="vertical"
            android:layout_width="fill_parent"
            android:layout_height="fill_parent"
            android:padding="5dp">
            <TabWidget
                android:id="@android:id/tabs"
                android:layout_width="fill_parent"
                android:layout_height="wrap_content" />
            <FrameLayout
                android:id="@android:id/tabcontent"
                android:layout_width="fill_parent"
                android:layout_height="fill_parent"
                android:padding="5dp"/>
            <TextView  
                android:id="@+id/item_title"
                android:layout_width="fill_parent" 
                android:layout_height="wrap_content" 
                android:textAppearance="?android:attr/textAppearanceMedium"
                android:padding="2dp"
                android:textSize="20dp" />
            <TextView  
                android:id="@+id/item_subtitle"
                android:layout_width="fill_parent" 
                android:layout_height="wrap_content" 
                android:padding="2dp"
                android:textSize="13dp" />
        </LinearLayout>
    </TabHost>
</LinearLayout>

Activity

public class TopNewsActivity extends ListActivity
{

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.listplaceholder);

        ArrayList<HashMap<String, String>> mylist = new ArrayList<HashMap<String, String>>();

        String xml = XMLfunctions.getTopNewsXML();
        Document doc = XMLfunctions.XMLfromString(xml);

        int numResults = XMLfunctions.numResults(doc);

        if ((numResults <= 0))
        {
            Toast.makeText(TopNewsActivity.this, "No Result Found", Toast.LENGTH_LONG).show();
            finish();
        }

        NodeList nodes = doc.getElementsByTagName("result");

    for (int i = 0; i < nodes.getLength(); i++) {                           
        HashMap<String, String> map = new HashMap<String, String>();    

        Element e = (Element)nodes.item(i);
        map.put("id", XMLfunctions.getValue(e, "id"));
        map.put("name", "Naam:" + XMLfunctions.getValue(e, "name"));
        map.put("Score", "Score: " + XMLfunctions.getValue(e, "score"));
        mylist.add(map);            
    }       

    ListAdapter adapter = new SimpleAdapter(this, mylist , R.layout.main, 
                    new String[] { "name", "Score" }, 
                    new int[] { R.id.item_title, R.id.item_subtitle });

    setListAdapter(adapter);

        final ListView lv = getListView();
        /*lv.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                @SuppressWarnings("unchecked")
                HashMap<String, String> o = (HashMap<String, String>) lv.getOnItemClickListener();

                Intent i = new Intent(view.getContext(), NewsDetails.class);
                i.putExtra("content_id", o.get("id"));
                i.putExtra("title", o.get("title"));
                startActivity(i);
                lv.setOnItemClickListener(this);

            }
        });*/

        final OnItemClickListener myClickListener = new OnItemClickListener()
        {
            @Override
            public void onItemClick(AdapterView<?> a, View view, int position, long id)
            {
                @SuppressWarnings("unchecked")
                HashMap<String, String> o = (HashMap<String, String>) lv.getOnItemClickListener();

                Intent i = new Intent(view.getContext(), NewsDetails.class);
                i.putExtra("content_id", o.get("id"));
                i.putExtra("title", o.get("naam"));
                startActivity(i);
            }
        };
        lv.setOnItemClickListener(myClickListener);
    }
}

TabActivity

 public class InfralineTabWidget extends TabActivity{

public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    Resources res = getResources(); // Resource object to get Drawables
    TabHost tabHost = (TabHost)getTabHost();  // The activity TabHost
    TabHost.TabSpec spec;  // Resusable TabSpec for each tab
    Intent intent;  // Reusable Intent for each tab

    // Create an Intent to launch an Activity for the tab (to be reused)
    intent = new Intent().setClass(this, TopNewsActivity.class);

    // Initialize a TabSpec for each tab and add it to the TabHost
    spec = tabHost.newTabSpec("topNews").setIndicator("Top News", res.getDrawable(R.drawable.tab_news)).setContent(intent);
    tabHost.addTab(spec);

    // Do the same for the other tabs
    intent = new Intent().setClass(this, PowerActivity.class);
    spec = tabHost.newTabSpec("power").setIndicator("Power", res.getDrawable(R.drawable.tab_power)).setContent(intent);
    tabHost.addTab(spec);

    tabHost.setCurrentTab(0);

}

 }

ListPlaceHolder.xml

 <?xml version="1.0" encoding="utf-8"?>

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"

android:orientation="vertical"

android:layout_width="fill_parent"

android:layout_height="fill_parent">    

<ListView
    android:id="@id/android:list"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:layout_weight="1"
    android:drawSelectorOnTop="false" />

  <TextView
    android:id="@id/android:empty"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:text="No data"/>
 </LinearLayout>

XMLFunction.java

 package com.infra.android.views;

 import java.io.BufferedReader;
 import java.io.FileReader;
 import java.io.IOException;
 import java.io.StringReader;
 import java.io.UnsupportedEncodingException;
 import java.net.MalformedURLException;
 import java.text.CharacterIterator;
 import java.text.StringCharacterIterator;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import org.apache.http.HttpEntity;
  import org.apache.http.HttpResponse;
 import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.jsoup.Jsoup;
import org.w3c.dom.CharacterData;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;

public class XMLfunctions {

public final static Document XMLfromString(String xml){

    Document doc = null;

    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    try {

        DocumentBuilder db = dbf.newDocumentBuilder();

        InputSource is = new InputSource();
        is.setCharacterStream(new StringReader(xml));
        doc = db.parse(is); 

    } catch (ParserConfigurationException e) {
        System.out.println("XML parse error: " + e.getMessage());
        return null;
    } catch (SAXException e) {
        System.out.println("Wrong XML file structure: " + e.getMessage());
        return null;
    } catch (IOException e) {
        System.out.println("I/O exeption: " + e.getMessage());
        return null;
    }

    return doc;

}


/** Returns element value
  * @param elem element (it is XML tag)
  * @return Element value otherwise empty String
  */
 public final static String getElementValue( Node elem ) {
     Node kid;
     if( elem != null){
         if (elem.hasChildNodes()){
             for( kid = elem.getFirstChild(); kid != null; kid = kid.getNextSibling() ){
                 if( kid.getNodeType() == Node.TEXT_NODE  ){
                     return kid.getNodeValue();
                 }
             }
         }
     }
     return "";
 }

 /*Start Parsing Top News XML*/
 public static String getTopNewsXML(){   
        String line = null;

        try {

            DefaultHttpClient httpClient = new DefaultHttpClient();
            HttpPost httpPost = new HttpPost("http://p-xr.com/xml");

            HttpResponse httpResponse = httpClient.execute(httpPost);
            HttpEntity httpEntity = httpResponse.getEntity();
            line = EntityUtils.toString(httpEntity);

        } catch (UnsupportedEncodingException e) {
            line = "<results status=\"error\"><msg>Can't connect to server</msg></results>";
        } catch (MalformedURLException e) {
            line = "<results status=\"error\"><msg>Can't connect to server</msg></results>";
        } catch (IOException e) {
            line = "<results status=\"error\"><msg>Can't connect to server</msg></results>";
        }

        return line;

}


public static int numResults(Document doc){     
    Node results = doc.getDocumentElement();
    int res = -1;

    try{
        res = Integer.valueOf(results.getAttributes().getNamedItem("count").getNodeValue());
    }catch(Exception e ){
        res = -1;
    }

    return res;
}

public static String getValue(Element item, String str) {       
    NodeList n = item.getElementsByTagName(str);        
    return XMLfunctions.getElementValue(n.item(0));
}   

   }

解决方案

You must get ClassCastException and if not that, at least NullPointerException because of the following line in your listener's code:

HashMap<String, String> o = (HashMap<String, String>) lv.getOnItemClickListener();

You should change it to

HashMap<String, String> o = (HashMap<String, String>) adapter.getItem(position);

in case that you are trying to access the underlying object of the list item renderer.

Edit

I've just tried out this application, and it works on my end (with dummy data, classes, etc.)
What i've changed though, is

final ListAdapter adapter = new SimpleAdapter(this, mylist, R.layout.main, 
        new String[] { "title" }, new int[] { R.id.item_title });
setListAdapter(adapter);

getListView().setOnItemClickListener(new OnItemClickListener()
{
    @Override
    public void onItemClick(AdapterView<?> a, View view, int position, long id)
    {
        HashMap<String, String> o = (HashMap<String, String>) adapter.getItem(position);

        Intent i = new Intent(TopNewsActivity.this, NewsDetails.class);
        i.putExtra("content_id", o.get("id"));
        i.putExtra("title", o.get("title"));
        startActivity(i);
    }
});

Edit 2

Rookie mistake focusing on the symptoms as we're sure the problem is there... Not that there wasn't, the notes above are standing.

But only when adopting the classes and layouts shared above, i realized, that you are actually using your TabView's layout as an itemrenderer for the list inside your TabView...

That main.xml shouldn't contain those two TextViews, they should be in a separate xml file (say: list_item.xml):

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical" android:layout_width="fill_parent"
    android:layout_height="wrap_content">
    <TextView android:id="@+id/item_title" android:layout_width="fill_parent"
        android:layout_height="wrap_content" android:textAppearance="?android:attr/textAppearanceMedium"
        android:padding="2dp" android:textSize="20dp" />
    <TextView android:id="@+id/item_subtitle"
        android:layout_width="fill_parent" android:layout_height="wrap_content"
        android:padding="2dp" android:textSize="13dp" />
</LinearLayout>

and your main.xml should look like

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent">
    <TabHost
        android:id="@android:id/tabhost"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent">
        <LinearLayout
            android:orientation="vertical"
            android:layout_width="fill_parent"
            android:layout_height="fill_parent"
            android:padding="5dp">
            <TabWidget
                android:id="@android:id/tabs"
                android:layout_width="fill_parent"
                android:layout_height="wrap_content" />
            <FrameLayout
                android:id="@android:id/tabcontent"
                android:layout_width="fill_parent"
                android:layout_height="fill_parent"
                android:padding="5dp"/>
        </LinearLayout>
    </TabHost>
</LinearLayout>

finally, when you initialize your list adapter, you should change it to use this list_item.xml:

final ListAdapter adapter =
    new SimpleAdapter(this, mylist, R.layout.list_item, new String[] 
        { "name", "Score" }, new int[] { R.id.item_title, R.id.item_subtitle });

and that's it.

Now it works, and doesn't have a whole new TabView (without any tabs) in each of your list items, neither has extra, useless and invisible TextViews in your main layout.

这篇关于Android的onItemClicklistener在列表视图不工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆