如何删除ListView中的特定项?

问题描述 投票:-1回答:2

在Android Studio中,我在主页面上有一个列表视图,可以继续添加多个课程。当我点击列表视图课程时,它会转到第二页。在第二页上有一个删除按钮,它将删除我点击的特定课程并带我回到主页面。

有人可以帮助我使用点击监听器删除按钮,以便上述程序工作?

java android
2个回答
1
投票

ListView获取项目列表并使用该列表显示您在屏幕上看到的内容。你需要做的是在第二页,只需从列表中删除该项,并在ListView的适配器上调用notifyDataSetChanged()方法。这将导致适配器再次创建所有项目,您将不再看到该已删除的项目。

编辑

只是让你入门的东西。如果您有一个包含所有正在添加的课程列表的课程,您只需在删除按钮上单击即可删除该课程。

class Courses {
    List<Course> courseList;

    //Your other members and functions

    void removeCourse(Course course) {
        courseList.remove(course);
    }
}

class Course {
    //Some details
}

button.setOnClickListener(new View.OnClickListener() {
         public void onClick(View v) {
             //Call that remvoeCourse method here
             courses.removeCourse(selectedCourse);
         }
});    

1
投票

如何删除ListView中的特定项?

你可以通过Share PreferencestartActivityForResult来解决你的问题。

使用startActivityForResult

在第一个活动中使用startActivityForResult()开始第二个活动;

Intent i = new Intent(this, SecondActivity.class);
startActivityForResult(i, 1);

单击删除功能时返回结果

Intent intent = new Intent();
intent.putExtra("result",position);
setResult(Activity.RESULT_OK,returnIntent);
finish();

在你的OnBackButton中添加它

Intent intent = new Intent();
setResult(Activity.RESULT_CANCELED, intent);
finish();

最后在First Activity中获得onActivityResult()的结果

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {

    if (requestCode == 1) {
        if(resultCode == Activity.RESULT_OK){
            String result=data.getIntExtra("position");
           // Do your operation here 
           // delete position you getting here from intent
        }
        if (resultCode == Activity.RESULT_CANCELED) {
            //Write your code if there's no result
        }
    }
}

使用共享首选项

保存您在共享偏好中的Listview项目的位置或ID,并在您的onBackPressed()函数中调用delete方法。在2个活动中执行这些操作。

PreferenceManager.getDefaultSharedPreferences(this).edit().putInt("position", position).commit();
onBackPressed();

在你的onRestart方法的第一个Activity do操作中

  @Override
    protected void onRestart() {
        super.onRestart();
        int position = PreferenceManager.getDefaultSharedPreferences(this).getInt("position", 0);
        // delete item from arraylist 
        // notify your adapter
    }
© www.soinside.com 2019 - 2024. All rights reserved.