jsw*_*jsw 4 android android-layout
我有一个ArrayList具有属性的对象的Object.name和Object.url.
我想循环遍历ArrayList并将Object的"name"应用于android ListView.我还希望保持Object的其他属性,以便我可以在onClick方法中调用"url"属性.
我现在拥有的是:
main_list.setAdapter(new ArrayAdapter<RomDataSet>(this, android.R.layout.simple_list_item_1, android.R.id.text1, mRoms));
Run Code Online (Sandbox Code Playgroud)
但显然这不是我需要的......
任何帮助,将不胜感激 :)
Vin*_*nay 10
1.)你有你的ArrayList:
main_list
Run Code Online (Sandbox Code Playgroud)
2.)在XML文件中创建一个ListView(比如main.xml)并获取其id.那是,给定:
<?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 xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/liveFeed"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
/>
</LinearLayout>
Run Code Online (Sandbox Code Playgroud)
做这样的事情:
ListView livefeed = (ListView)this.findViewById(R.id.liveFeed);
Run Code Online (Sandbox Code Playgroud)
在你的活动中(如果你在其他地方,比如OnClickListener,将"this"替换为作为变量传递给OnClickListener的View变量).
3.)定义ArrayAdapter.请注意,其中一个参数(在您的情况下为第三个参数)将是TextView ID.这是因为默认情况下,ArrayAdapter类在ListView中返回TextView.如果覆盖ArrayAdapter类,则可以使用自定义布局在ListView中包含具有自定义视图的项目,但这对于您在问题中概述的内容不是必需的,并且您似乎已经获得了它.
4.)将适配器设置为ListView(给定名为'aa'的ArrayAdapter):
livefeed.setAdapter(aa);
Run Code Online (Sandbox Code Playgroud)
现在,ArrayAdapter的工作方式是调用每个Object的toString()方法,并将ListView中的每个TextView设置为此String.因此,在Object的类中创建一个返回其name属性的toString()方法:
public String toString(){return name;} //assuming name is a String
Run Code Online (Sandbox Code Playgroud)
另请注意,如果您将对象添加到ArrayList,请通知ArrayAdapter您可以相应地更新ListView并进行修改(给定名为'aa'的ArrayAdapter):
aa.notifyDataSetChanged();
Run Code Online (Sandbox Code Playgroud)
如果您需要更多帮助,请与我们联系.与往常一样,如果这回答了您的问题,请检查答案复选标记.
另请注意,您可能希望在您的activity和Object类之间交叉引用ArrayAdapter和ArrayList.为了这样做,将这些字段设置为静态非常有用.
编辑:
当您单击ListView中的项目时,您还想知道如何访问特定的对象.这是(给定您的ListView命名为livefeed):
livefeed.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> a, View v, int position, long id) {
//in here you may access your Object by using livefeed.getItemAtPosition(position)
//for example:
Object current = livefeed.getItemAtPosition(position);
//do whatever with the Object's data
}
});
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3032 次 |
| 最近记录: |