2011-04-22 51 views
2

任何人都可以帮我解决我的问题。我有一个TabActivity每个选项卡接触打开一个新的活动,此时扩展ListActivity我得到所需项目的列表,我想通过使用OnItemClickListener进行点击。Android onItemClicklistener在列表视图不工作

我附加了我的main.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"> 
    <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> 

活动

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)); 
} 

    } 
+1

能否请您分享您的'ListActivities'之一的代码与'OnItemClickListener'的实现?谢谢。 – rekaszeru 2011-04-22 09:33:18

+0

@rekaszeru我已添加ListActivity的代码 – ReNa 2011-04-22 09:47:26

+0

请查看我的帖子,如果LogCat中存在异常,请分享它们。谢谢! – rekaszeru 2011-04-22 09:55:25

回答

5

你必须得到ClassCastException,如果没有,至少NullPointerException因为在你的听众的以下代码行的:

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

您应将其更改为

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

在您尝试访问列表项渲染器的底层对象的情况。

编辑

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

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); 
    } 
}); 

编辑2

新手的错误集中在症状我们相信这个问题是存在的......不是说有没有,上面的注释是站立的。

但是只有当采用上面分享的类和布局时,我意识到,你实际上正在使用你的TabView的布局作为你的TabView中的列表的itemrenderer ...

main.xml不应该包含这两个TextViews,他们应该是在一个单独的XML文件(比如: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> 

和你main.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"> 
    <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> 

最后,当你初始化你的列表适配器时,你应该改变它来使用这个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 }); 

就是这样。

现在它可以工作,并且在每个列表项中没有全新的TabView(没有任何选项卡),但在主布局中都没有额外的,无用的和不可见的TextViews

0

试试这个编辑的文件:

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("title", XMLfunctions.getValue(e, "title")); 
    mylist.add(map);    
}  

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



final ListView lv = getListView(); 
setListAdapter(adapter); 
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.getItemAtPosition(position); 

     Toast.makeText(getApplicationContext(),"Inside onItemClick",Toast_LONG).show(); 
     /* 
     Intent i = new Intent(view.getContext(), NewsDetails.class); 
     i.putExtra("content_id", o.get("id")); 
     i.putExtra("title", o.get("title")); 
     startActivity(i);*/ 
    } 
}); 



} 

} 
+0

@Kartik仍然没有工作 – ReNa 2011-04-22 10:59:09

+0

@Rahul:好吧看到编辑的答案,并告诉我它是否工作。 – 2011-04-22 11:01:32

+0

@kartik仍然没有任何事情发生onItemClick不工作调试器绕过OnItemClick函数 – ReNa 2011-04-22 11:11:56

2

我使用的RatingBar时,也有类似的问题。

在我的情况下,我不得不使用android:isIndicator="true"从RatingBar中删除焦点。

我在Android中看到很多关于ListView的类似问题。一般而言,人们在他们的布局中使用一些小部件,这会重写默认的ListView点击处理。

我的答案是检查所有的小部件不拦截点击事件。

0

这里有一个原因,咬我最近:如果您添加clicklistener由适配器,它掩盖了longclick行为返回的视图....