首页 > 解决方案 > 从 ListView 获取列表项

问题描述

当单击该项目时,我有兴趣在ListView 中获取对列表项的对象引用。我的自定义项目 XML 上的每个项目都包含一个hidden默认情况下的 Button 和一个 TextView。单击某个项目应将其更改visibilityvisible
这就是我的意思,在集成图形编辑器中完成。

在此处输入图像描述

应该变成这个

在此处输入图像描述

这是我getView对 AdapterView的自定义


@Override
public View getView(int position, View v, ViewGroup viewGroup){

    if(v==null){
        LayoutInflater li= LayoutInflater.from(getContext());
        v= li.inflate(R.layout.custom_list_item, null);
    }

    Student s= getItem(position);
    TextView name= v.findViewById(R.id.txt_name);
    TextView surname= v.findViewById(R.id.txt_surname);
    TextView id= v.findViewById(R.id.txt_id);

    //following methods come from my Student class
    if(s != null){
        name.setText(s.getName());
        surname.setText(s.getSurname());
        id.setText(s.getId());
    }
    return v;
}

这就是我(想要)在我的活动中做的事情,但现在还不行。


ListView list= findViewById(R.id.advanced_list);
    final StudentAdapter adapter= new StudentAdapter(
            this,
            R.layout.custom_list_item,
            getStudents()
    );

    list.setAdapter(adapter);


    list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

            TextView tel= findViewById(R.id.txt_tel);
            Button delete= findViewById(R.id.btn_delete);

            tel.setVisibility(View.VISIBLE);
            delete.setVisibility(View.VISIBLE);
        }
    });

标签: androidandroid-studio

解决方案


list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

        TextView tel= findViewById(R.id.txt_tel);
        Button delete= findViewById(R.id.btn_delete);

        tel.setVisibility(View.VISIBLE);
        delete.setVisibility(View.VISIBLE);
    }
});

您试图View在布局中查找 s Activity,但它们在View您作为参数获得的 s 中。你可以像这样修复它:

...
TextView tel= view.findViewById(R.id.txt_tel);
Button delete= view.findViewById(R.id.btn_delete);
...

推荐阅读