在 Android 中添加 ListView 子项文本

2022-09-01 06:27:24

我创建了一个 RSS 阅读器,用于列出列表视图中的项目。我也想在每个项目下面有一个日期,但我不知道该怎么做。我需要某人的帮助才能使子项文本显示从 RSS 源检索到的 pubDate。

这是我的类的代码:

public class RSSReader extends Activity implements OnItemClickListener
{
    public final String RSSFEEDOFCHOICE = "http://app.calvaryccm.com/mobile/android/v1/devos";

    public final String tag = "RSSReader";
    private RSSFeed feed = null;

    /** Called when the activity is first created. */

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

        // go get our feed!
        feed = getFeed(RSSFEEDOFCHOICE);

        // display UI
        UpdateDisplay();
    }

    private RSSFeed getFeed(String urlToRssFeed)
    {
        try
        {
            // setup the url
           URL url = new URL(urlToRssFeed);

           // create the factory
           SAXParserFactory factory = SAXParserFactory.newInstance();
           // create a parser
           SAXParser parser = factory.newSAXParser();

           // create the reader (scanner)
           XMLReader xmlreader = parser.getXMLReader();
           // instantiate our handler
           RSSHandler theRssHandler = new RSSHandler();
           // assign our handler
           xmlreader.setContentHandler(theRssHandler);
           // get our data via the url class
           InputSource is = new InputSource(url.openStream());
           // perform the synchronous parse           
           xmlreader.parse(is);
           // get the results - should be a fully populated RSSFeed instance, or null on error
           return theRssHandler.getFeed();
        }
        catch (Exception ee)
        {
            // if we have a problem, simply return null
            System.out.println(ee.getMessage());
            System.out.println(ee.getStackTrace());
            System.out.println(ee.getCause());
            return null;
        }
    }
    public boolean onCreateOptionsMenu(Menu menu) 
    {
        super.onCreateOptionsMenu(menu);
        menu.add(Menu.NONE, 0, 0, "Refresh");
        Log.i(tag,"onCreateOptionsMenu");
        return true;
    }

    public boolean onOptionsItemSelected(MenuItem item){
        switch (item.getItemId()) {
        case 0:

            Log.i(tag,"Set RSS Feed");
            return true;
        case 1:
            Log.i(tag,"Refreshing RSS Feed");
            return true;
        }
        return false;
    }

    private void UpdateDisplay()
    {
        TextView feedtitle = (TextView) findViewById(R.id.feedtitle);
        TextView feedpubdate = (TextView) findViewById(R.id.feedpubdate);
        ListView itemlist = (ListView) findViewById(R.id.itemlist);


        if (feed == null)
        {
            feedtitle.setText("No RSS Feed Available");
            return;
        }

        if(feedtitle != null)
            feedtitle.setText(feed.getTitle());
        if(feedpubdate != null)
            feedpubdate.setText(feed.getPubDate());


        ArrayAdapter<RSSItem> adapter = new ArrayAdapter<RSSItem>(this,android.R.layout.simple_list_item_1,feed.getAllItems());

        itemlist.setAdapter(adapter);

        itemlist.setOnItemClickListener(this);

        itemlist.setSelection(0);
    }

    @Override
    public void onItemClick(AdapterView parent, View v, int position, long id)
    {
        //Log.i(tag,"item clicked! [" + feed.getItem(position).getTitle() + "]");       

        Intent itemintent = new Intent(this,ShowDescription.class);

        Bundle b = new Bundle();
        b.putString("title", feed.getItem(position).getTitle());
        b.putString("description", feed.getItem(position).getDescription());
        b.putString("link", feed.getItem(position).getLink());
        b.putString("pubdate", feed.getItem(position).getPubDate());

        itemintent.putExtra("android.intent.extra.INTENT", b);

        startActivity(itemintent);
    }
}

这是我的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">
 <TextView  
android:layout_width="fill_parent" 
android:layout_height="wrap_content" 
android:text="Android RSSReader"
android:id="@+id/feedtitle"/>
<TextView  
android:layout_width="fill_parent" 
android:layout_height="wrap_content" 
android:text=""
android:id="@+id/feedpubdate"/>
<ListView
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:id="@+id/itemlist"

android:fastScrollEnabled="true"/>    
 </LinearLayout>

这就是它现在在Eclipse中的样子:

ListView Currently

这是它运行的样子:

In Process

如何使子项文本显示从RSS源检索到的pubDate?


答案 1

最简单的解决方案可能是将 您正在使用的 和 替换为 预定义布局。此布局由两个组成,分别具有(“项目”)和(“子项目”)的ID,您需要将其作为工作的参考。ArrayAdapterandroid.R.layout.simple_list_item_1SimpleAdapterandroid.R.layout.simple_list_item_2TextViewandroid.R.id.text1android.R.id.text2SimpleAdapter

通过查看构造函数,您会注意到,除了实例和布局资源的 ID 之外,它还需要三个对您来说可能是新的参数:SimpleAdapterContext

  • 一个实例,您可以在其中放置要显示的元素。元素的形式是 ,即类似于由名称/值对形式的属性组成的结构。例如,您可以分别使用 和 作为每个 RSS 项目的标题和日期的键。List<? extends Map<String, ?>>ListViewMap"title""date"
  • 一个字符串数组,用于在 中放置要在 上显示的每个映射中的键的名称。ListView
  • 一个整数数组,您需要在其中将各个部分的 ID 放在列表项视图中,在该视图中,您希望显示由前面的字符串数组中的键引用的单个元素。例如,如果要分别在“项”和“子项”视图中显示 RSS 项的标题和日期,则可以用作字符串数组参数和此参数。new String[] { "title", "date" }new int[] { android.R.id.text1, android.R.id.text2 }

一个粗略的代码示例,只是为了给你这个想法:

List<Map<String, String>> data = new ArrayList<Map<String, String>>();
for (RSSItem item : feed.getAllItems()) {
    Map<String, String> datum = new HashMap<String, String>(2);
    datum.put("title", item.getTitle());
    datum.put("date", item.getDate().toString());
    data.add(datum);
}
SimpleAdapter adapter = new SimpleAdapter(this, data,
                                          android.R.layout.simple_list_item_2,
                                          new String[] {"title", "date"},
                                          new int[] {android.R.id.text1,
                                                     android.R.id.text2});
itemList.setAdapter(adapter);

文档指出“地图包含每行的数据,并且应包括在 from 参数中指定的所有条目”,因此标题和日期应始终存在。

请注意,这一切都在我的头顶上。我实际上还没有测试过所有的代码,所以你很可能会遇到一些怪癖或错误,你需要在上升的过程中进行调整或修复。


答案 2

你应该有一个item_list.xml文件,如下所示:

    <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:padding="6dp" >

    <TextView
        android:id="@+id/page_title"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:textColor="#D8000000"
        android:textSize="16sp"
        android:textStyle="bold" />

    <TextView
        android:id="@+id/page_date"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_below="@id/page_title"
        android:ellipsize="marquee"
        android:lines="3"
        android:marqueeRepeatLimit="marquee_forever"
        android:textColor="#D8000000"
        android:textSize="12sp" />

</RelativeLayout>

并在方法 getview 中的 listadapter 中:

View row = convertView;
LayoutInflater inflater = ((Activity) mContext).getLayoutInflater();
row = inflater.inflate(R.layout.item_list, parent, false);

TextView listTitle = (TextView) row.findViewById(R.id.page_title);
 listTitle.setText(title);

TextView date = (TextView) row.findViewById(R.id.page_date); 
date.setText( <here put your date from RSS feed>);

return row;

这应该可以做到!


推荐