在andriod ListView中,最后一个元素重复显示

时间:2017-12-02 03:12:36

标签: android listview

我创建了一个包含两个文本字段的自定义列表视图。显示姓名和年龄。 我给出了一个包含三个对象的示例数组。但每次只显示数组中ListView的所有位置的最后一个元素。

这是我的主要活动:

package com.sridatta.listview;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.ArrayAdapter;
import android.widget.ListView;



public class MainActivity extends AppCompatActivity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        details[] objects={new details("datta",19),new details("siva",20),new details("kd",18)};
     CustomArrayAdapter adapter=new CustomArrayAdapter(this,R.id.listtype,objects);
     ListView lv=(ListView)findViewById(R.id.list_view);
     lv.setAdapter(adapter);

    }
}

这是我的Custom ArrrayAdapter类:

public class CustomArrayAdapter extends ArrayAdapter<details> {


public CustomArrayAdapter(@NonNull Context context, int resource, @NonNull details[] objects) {
    super(context, resource, objects);
}

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

    if(convertView==null){Context context=getContext();
    LayoutInflater inflater=(LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        convertView=inflater.inflate(R.layout.list_type,null);
        }
    TextView tv1=(TextView)convertView.findViewById(R.id.name);
    TextView tv2=(TextView)convertView.findViewById(R.id.age);
    tv1.setText(getItem(position).name);
    tv2.setText(Integer.toString(getItem(position).age));
    return convertView;
}
}

这里是详细课程

public class details {
static String name;
static int age;
public details(String name,int age){
    this.name=name;
    this.age=age;
}
}

任何帮助都会感激不尽。

1 个答案:

答案 0 :(得分:0)

您正在使用回收视图,当Android认为您可以在屏幕上看到它时将生成回收视图。例如,向上滚动时,最后一项可能会从屏幕隐藏,它将重复显示最后一项。初始布局时只需要设置文本。您应该像这样更改代码:

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

    if(convertView==null){Context context=getContext();
        LayoutInflater inflater=(LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        convertView=inflater.inflate(R.layout.list_type,null);
    }
    //update the text when view show up
    TextView tv1=(TextView)convertView.findViewById(R.id.name);
    TextView tv2=(TextView)convertView.findViewById(R.id.age); 
    tv1.setText(getItem(position).name);
    tv2.setText(Integer.toString(getItem(position).age));
    return convertView;
}

注意你的对象类,你想要它们作为不同的对象,但是静态会将它们的值满足到相同的内存位置。你应该删除静态,以便将它们存储为唯一对象。

public class details {
    private String name;
    private int age;
    public details(String name,int age){
        this.name=name;
        this.age=age;
    }
}