如何在自定义对象的android中使用ArrayAdapter

如何在Listview中使用自定义对象的属性。如果我实现一个带有字符串列表的ArrayAdapter,它在Listview中会很好地显示,但是当我使用一个自定义对象的列表时,它只是输出内存地址。


我到目前为止的代码:


ArrayList<CustomObject> allObjects = new ArrayList<>();


allObjects.add("title", "http://url.com"));



  ArrayAdapter<NewsObject> adapter = new ArrayAdapter<NewsObject>(this,

                android.R.layout.simple_list_item_1, android.R.id.text1, allNews);



        // Assign adapter to ListView

        listView.setAdapter(adapter);



        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {

            @Override

            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {


                Uri uri = Uri.parse( "http://www.google.com" );

                startActivity(new Intent(Intent.ACTION_VIEW, uri));

            }

        });

这里有一个类似的问题,但这不是我所需要的,因为我只需要在列表视图中显示标题,并且当他们单击时提取URL即可。


UYOU
浏览 765回答 3
3回答

倚天杖

ArrayAdapter显示toString()方法返回的值,因此您将需要在自定义Object类中重写此方法以返回所需的String。您还需要至少具有该URL的getter方法,以便可以在click事件中检索该方法。public class NewsObject {&nbsp; &nbsp; private String title;&nbsp; &nbsp; private String url;&nbsp; &nbsp; public NewsObject(String title, String url) {&nbsp; &nbsp; &nbsp; &nbsp; this.title = title;&nbsp; &nbsp; &nbsp; &nbsp; this.url = url;&nbsp; &nbsp; }&nbsp; &nbsp; public String getUrl() {&nbsp; &nbsp; &nbsp; &nbsp; return url;&nbsp; &nbsp; }&nbsp; &nbsp; @Override&nbsp; &nbsp; public String toString() {&nbsp; &nbsp; &nbsp; &nbsp; return title;&nbsp; &nbsp; }&nbsp; &nbsp; ...}在该onItemClick()方法中,position将是自定义对象的ArrayList中与单击的列表项相对应的索引。检索URL,对其进行解析,然后调用startActivity()。listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {&nbsp; &nbsp; &nbsp; &nbsp; @Override&nbsp; &nbsp; &nbsp; &nbsp; public void onItemClick(AdapterView<?> parent, View view, int position, long id) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; NewsObject item = allNews.get(position);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; String url = item.getUrl();&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; Uri uri = Uri.parse(url);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; startActivity(new Intent(Intent.ACTION_VIEW, uri));&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; });请注意,我假设您的自定义类是NewsObject,因为这是您的Adapter示例所使用的。
打开App,查看更多内容
随时随地看视频慕课网APP