如何使用 baseadapter 自定义列表视图

Posted

技术标签:

【中文标题】如何使用 baseadapter 自定义列表视图【英文标题】:How to customize listview using baseadapter 【发布时间】:2013-04-26 08:55:53 【问题描述】:

我想像这样创建一个自定义的ListView

我认为我必须使用BaseAdapter,但我不知道。

【问题讨论】:

查看链接androidhive.info/2012/02/…中的教程 【参考方案1】:

main.xml:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_
    android:layout_
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context=".MainActivity" >

    <ListView
        android:id="@+id/list"
        android:layout_
        android:layout_
        android:layout_alignParentLeft="true"
        android:layout_alignParentTop="true" >

    </ListView>

</RelativeLayout>

custom.xml:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_
    android:layout_
    android:orientation="vertical" >

    <LinearLayout
        android:layout_
        android:layout_ >

        <LinearLayout
            android:layout_
            android:layout_
            android:orientation="vertical" >

            <LinearLayout
                android:layout_
                android:layout_
                android:orientation="vertical" >

                <TextView
                    android:id="@+id/title"
                    android:layout_
                    android:layout_
                    android:text="Video1"
                    android:textAppearance="?android:attr/textAppearanceLarge"
                    android:textColor="#339966"
                    android:textStyle="bold" />
            </LinearLayout>

            <LinearLayout
                android:layout_
                android:layout_
                android:orientation="vertical" >

                <TextView
                    android:id="@+id/detail"
                    android:layout_
                    android:layout_
                    android:text="video1"
                    android:textColor="#606060" />
            </LinearLayout>
        </LinearLayout>

        <ImageView
            android:id="@+id/img"
            android:layout_
            android:layout_
            android:src="@drawable/ic_launcher" />

    </LinearLayout>

</LinearLayout>

main.java:

package com.example.sample;

import android.app.Activity;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;


public class MainActivity extends Activity 

    ListView l1;
    String[] t1="video1","video2";
    String[] d1="lesson1","lesson2";
    int[] i1 =R.drawable.ic_launcher,R.drawable.ic_launcher;


    @Override
    protected void onCreate(Bundle savedInstanceState) 
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        l1=(ListView)findViewById(R.id.list);
        l1.setAdapter(new dataListAdapter(t1,d1,i1));
    

    class dataListAdapter extends BaseAdapter 
        String[] Title, Detail;
        int[] imge;

        dataListAdapter() 
            Title = null;
            Detail = null;
            imge=null;
        

        public dataListAdapter(String[] text, String[] text1,int[] text3) 
            Title = text;
            Detail = text1;
            imge = text3;

        

        public int getCount() 
            // TODO Auto-generated method stub
            return Title.length;
        

        public Object getItem(int arg0) 
            // TODO Auto-generated method stub
            return null;
        

        public long getItemId(int position) 
            // TODO Auto-generated method stub
            return position;
        

        public View getView(int position, View convertView, ViewGroup parent) 

            LayoutInflater inflater = getLayoutInflater();
            View row;
            row = inflater.inflate(R.layout.custom, parent, false);
            TextView title, detail;
            ImageView i1;
            title = (TextView) row.findViewById(R.id.title);
            detail = (TextView) row.findViewById(R.id.detail);
            i1=(ImageView)row.findViewById(R.id.img);
            title.setText(Title[position]);
            detail.setText(Detail[position]);
            i1.setImageResource(imge[position]);

            return (row);
        
    

试试这个。

【讨论】:

i 使用此代码,但引发以下异常 java.lang.ArrayIndexOutOfBoundsException: length=10;索引=10 你必须使用 ViewHolder 来提高性能...检查这个***.com/questions/19469073/… @ShaktisinhJadeja 布局充气器来自活动类,因为适配器是在其中实现的。尝试 - LayoutInflater.from(context) 如果它是一个独立的类。【参考方案2】:
public class ListElementAdapter extends BaseAdapter

    String[] data;
    Context context;
    LayoutInflater layoutInflater;


    public ListElementAdapter(String[] data, Context context) 
        super();
        this.data = data;
        this.context = context;
        layoutInflater = LayoutInflater.from(context);
    

    @Override
    public int getCount() 

        return data.length;
    

    @Override
    public Object getItem(int position) 

        return null;
    

    @Override
    public long getItemId(int position) 

        return position;
    

    @Override
    public View getView(int position, View convertView, ViewGroup parent) 


        convertView= layoutInflater.inflate(R.layout.item, null);

        TextView txt=(TextView)convertView.findViewById(R.id.text);

        txt.setText(data[position]);



        return convertView;
    

只需在 Main Activity 中调用 ListElementAdapter 并将 Adapter 设置为 ListView。

【讨论】:

我该如何使用它? ListElementAdapter 适配器 = new ListElementAdapter(array, this);将不起作用,因为它扩展了 BaseAdapter 并且 BaseAdapter 是一个抽象类 因为答案太旧并且 ListView 在 Android 中已被弃用。我建议你 - 改用 Recycler View。谢谢【参考方案3】:

创建您自己的 BaseAdapter 类并按如下方式使用它。

 public class NotificationScreen extends Activity


@Override
protected void onCreate_Impl(Bundle savedInstanceState)

    setContentView(R.layout.notification_screen);

    ListView notificationList = (ListView) findViewById(R.id.notification_list);
    NotiFicationListAdapter notiFicationListAdapter = new NotiFicationListAdapter();
    notificationList.setAdapter(notiFicationListAdapter);

    homeButton = (Button) findViewById(R.id.home_button);




制作您自己的 BaseAdapter 类及其单独的 xml 文件。

public class NotiFicationListAdapter  extends BaseAdapter

private ArrayList<HashMap<String, String>> data;
private LayoutInflater inflater=null;


public NotiFicationListAdapter(ArrayList data)

this.data=data;        
    inflater =(LayoutInflater)baseActivity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);




public int getCount() 

 return data.size();




public Object getItem(int position) 

 return position;




public long getItemId(int position) 

    return position;




public View getView(int position, View convertView, ViewGroup parent) 

View vi=convertView;
    if(convertView==null)

    vi = inflater.inflate(R.layout.notification_list_item, null);

    ImageView compleatImageView=(ImageView)vi.findViewById(R.id.complet_image);
    TextView name = (TextView)vi.findViewById(R.id.game_name); // name
    TextView email_id = (TextView)vi.findViewById(R.id.e_mail_id); // email ID
    TextView notification_message = (TextView)vi.findViewById(R.id.notification_message); // notification message



    compleatImageView.setBackgroundResource(R.id.address_book);
    name.setText(data.getIndex(position));
    email_id.setText(data.getIndex(position));
    notification_message.setTextdata.getIndex(position));

    return vi;


  

BaseAdapter xml 文件。

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/inner_layout"
android:layout_
android:layout_
android:layout_marginBottom="5dp"
android:layout_marginLeft="10dp"
android:layout_weight="4"
android:background="@drawable/list_view_frame"
android:gravity="center_vertical"
android:padding="5dp" >

<TextView
    android:id="@+id/game_name"
    android:layout_
    android:layout_
    android:text="Game name"
    android:textColor="#FFFFFF"
    android:textSize="15dip"
    android:textStyle="bold"
    android:typeface="sans" />

<TextView
    android:id="@+id/e_mail_id"
    android:layout_
    android:layout_
    android:layout_below="@id/game_name"
    android:layout_marginTop="1dip"
    android:text="E-Mail Id"
    android:textColor="#FFFFFF"
    android:textSize="10dip" />

<TextView
    android:id="@+id/notification_message"
    android:layout_
    android:layout_
    android:layout_below="@id/game_name"
    android:layout_toRightOf="@id/e_mail_id"
    android:paddingLeft="5dp"
    android:text="Notification message"
    android:textColor="#FFFFFF"
    android:textSize="10dip" />



<ImageView
    android:id="@+id/complet_image"
    android:layout_
    android:layout_
    android:layout_alignParentRight="true"
    android:layout_centerVertical="true"
    android:layout_marginBottom="30dp"
    android:layout_marginRight="10dp"
    android:src="@drawable/complete_tag"
    android:visibility="invisible" />

</RelativeLayout>

相应地更改并使用。

【讨论】:

【参考方案4】:

我建议使用自定义的Adapter,先创建一个Xml-file,例如layout/customlistview.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_ android:layout_ >
    <ImageView
        android:id="@+id/image"
        android:layout_alignParentRight="true"
        android:paddingRight="4dp" />
    <TextView
        android:id="@+id/title"
        android:layout_toLeftOf="@id/image"
        android:layout_
        android:layout_
        android:textSize="23sp"
        android:maxLines="1" />
    <TextView
        android:id="@+id/subtitle"
        android:layout_toLeftOf="@id/image" android:layout_below="@id/title"
        android:layout_
        android:layout_ /> 
</RelativeLayout>

假设你有一个这样的自定义类

public class CustomClass 

    private long id;
    private String title, subtitle, picture;

    public CustomClass () 
    

    public CustomClass (long id, String title, String subtitle, String picture) 
        this.id = id;
        this.title= title;
        this.subtitle= subtitle;
        this.picture= picture;
    
    //add getters and setters

CustomAdapter.java 使用 xml 布局

public class CustomAdapter extends ArrayAdapter 

private Context context;
private int resource;
private LayoutInflater inflater;

public CustomAdapter (Context context, List<CustomClass> values)  // or String[][] or whatever

    super(context, R.layout.customlistviewitem, values);

    this.context = context;
    this.resource = R.layout.customlistview;
    this.inflater = LayoutInflater.from(context);


@Override
public View getView(int position, View convertView, ViewGroup parent) 

    convertView = (RelativeLayout) inflater.inflate(resource, null);

    CustomClass item = (CustomClass) getItem(position);

    TextView textviewTitle = (TextView) convertView.findViewById(R.id.title);
    TextView textviewSubtitle = (TextView) convertView.findViewById(R.id.subtitle);
    ImageView imageview = (ImageView) convertView.findViewById(R.id.image);

    //fill the textviews and imageview with the values
    textviewTitle = item.getTtile();
    textviewSubtitle = item.getSubtitle();

    if (item.getAfbeelding() != null) 
        int imageResource = context.getResources().getIdentifier("drawable/" + item.getImage(), null, context.getPackageName());
        Drawable image = context.getResources().getDrawable(imageResource);
    
    imageview.setImageDrawable(image);

    return convertView;
    

你做到了吗?如果您想了解更多信息,请随时询问:)

编辑:将适配器更改为适合列表,而不仅仅是列表

【讨论】:

对不起;请解释我如何在包含名为“lv”的列表视图的活动中使用此类,以及此行中“toerismelistviewitem”的目的是什么:“super(context, R.layout.toerismelistviewitem, values);” 您好,只需填写您的 Xml 文件的名称,因此在您的情况下它将是 super(context, R.layout.lv, values) - 我忘了重命名它:) 和我刚得到一个 List 值,但可能希望你的字符串在一个二维列表中,因为你有一个标题和副标题,你可以随心所欲地改变它,记住这一点。 我使用 List 而不是 List 所以它会同时提供字符串和图像的 url。看看我的编辑,我希望现在很清楚......【参考方案5】:
private class ObjectAdapter extends BaseAdapter 

    private Context context;
    private List<Object>objects;

    public ObjectAdapter(Context context, List<Object> objects) 
        this.context = context;
        this.objects = objects;
    

    @Override
    public int getCount() 
        return objects.size();
    

    @Override
    public Object getItem(int position) 
        return objects.get(position);
    

    @Override
    public long getItemId(int position) 
        return position;
    

    @Override
    public View getView(int position, View convertView, ViewGroup parent) 
        ViewHolder holder;

        if(convertView==null)
            holder = new ViewHolder();
            convertView = LayoutInflater.from(context).inflate(android.R.layout.simple_list_item_1, parent, false);
            holder.text = (TextView) convertView.findViewById(android.R.id.text1);
            convertView.setTag(holder);
        else
            holder = (ViewHolder) convertView.getTag();
        

        holder.text.setText(getItem(position).toString()));
        return convertView;
    

    class ViewHolder 
        TextView text;
    

【讨论】:

我该如何使用它? ObjectAdapter 适配器 = new ObjectAdapter(this, objects);将不起作用,因为它扩展了 BaseAdapter 并且 BaseAdapter 是一个抽象类

以上是关于如何使用 baseadapter 自定义列表视图的主要内容,如果未能解决你的问题,请参考以下文章

使用带有自定义 baseadapter 的 arraylist 错误地删除列表视图项位置

如何在 BaseAdapter 中使用 getFilter() 过滤 ListView

使用 CardView BaseAdapter OnItemClick 自定义 ListView

我如何使用 baseadapter 过滤列表视图

Android - 带有自定义 BaseAdapter 的 Gridview,在位置获得点击视图

如何将数据添加到 listView 的自定义 BaseAdapter - Android