【发布时间】:2017-05-26 10:53:16
【问题描述】:
是否可以在活动中为 listView 项目按钮绑定 onClickListener?我的 listView 项目有名称、删除和编辑按钮。 listView 项目存储在 List 中。
exercises_list_view_item.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="40dp"
android:orientation="vertical"
android:paddingLeft="10dp"
android:paddingRight="10dp">
<Button
android:id="@+id/deleteExerciseBtn"
android:layout_width="40dp"
android:layout_height="40dp"
android:layout_alignParentRight="true"
android:background="@android:drawable/ic_delete" />
<Button
android:id="@+id/editExerciseBtn"
android:layout_width="26dp"
android:layout_height="26dp"
android:layout_marginRight="5dp"
android:layout_marginTop="7dp"
android:layout_toLeftOf="@id/deleteExerciseBtn"
android:background="@drawable/edit_btn" />
<TextView
android:id="@+id/exerciseName"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_centerVertical="true"
android:layout_marginRight="8dp"
android:layout_toLeftOf="@id/editExerciseBtn"
android:ellipsize="end"
android:maxLines="1"
android:text="This is a Large text with fill width"
android:textColor="#000000"
android:textSize="18sp" />
</RelativeLayout>
活动中的代码:
@Override
public void onButtonClickListner(int position, String value) {
Toast.makeText(create_workout.this, "Button click " + value,
Toast.LENGTH_SHORT).show();
}
List<WorkoutExercise> workoutExercises = workout.getWorkoutExercises();
ListView exercisesList = (ListView) findViewById(R.id.exerciseListView);
WorkoutExerciseListAdapter listAdapter = new WorkoutExerciseListAdapter(this, R.layout.exercises_list_view_item, workoutExercises);
listAdapter.setCustomButtonListener(create_workout.this);
exercisesList.setAdapter(listAdapter);
由于 WorkoutExerciseListAdapted 有很多代码,我把它贴在这里:https://pastebin.com/FYNVVQnS
我想做的是: 如果用户单击编辑按钮,我需要将练习对象传递给另一个活动进行编辑。 如果用户单击删除按钮,我需要从 List 中删除该项目并更新 listView(使用 notifyDataSetChanged() ?)
我试图通过 stackoverflow 和 google 寻找答案,但它要么不起作用,要么我的应用程序开始崩溃。 几个尝试过的例子: http://www.c-sharpcorner.com/UploadFile/9e8439/create-custom-listener-on-button-in-listitem-listview-in-a/ Adding an onclicklistener to listview (android) 等等..
如果有任何建议,我将不胜感激。感谢您的宝贵时间。
【问题讨论】:
标签: android listview onclicklistener