在Android Studio中,我在主页上有一个列表视图,可以在其中继续添加多个课程。当我点击列表视图课程时,将带我进入第二页。在第二页上有一个删除按钮,它将删除我单击的特定课程并带我回到主页。
有人可以通过点击侦听器的“删除”按钮帮助我,以使上述过程正常进行吗?
答案 0 :(得分: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 :(得分:1)
如何删除ListView中的特定项目?
您可以通过Share Preference
或startActivityForResult
解决问题。
使用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();
最后在“第一个活动”的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();
在您的第一个Activity中,使用onRestart
方法进行操作
@Override
protected void onRestart() {
super.onRestart();
int position = PreferenceManager.getDefaultSharedPreferences(this).getInt("position", 0);
// delete item from arraylist
// notify your adapter
}