您好,登錄后才能下訂單哦!
在Android中,要實現ListView的項編輯功能,你可以采用以下步驟:
list_item_edit.xml
的布局文件:<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<EditText
android:id="@+id/edit_text"
android:layout_width="0dp"
android:layout_weight="1"
android:layout_height="wrap_content"
android:hint="Enter text"/>
<Button
android:id="@+id/button_save"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Save"/>
</LinearLayout>
EditableListAdapter
的類:public class EditableListAdapter extends BaseAdapter {
private List<String> data;
private LayoutInflater inflater;
public EditableListAdapter(Context context, List<String> data) {
this.data = data;
inflater = LayoutInflater.from(context);
}
@Override
public int getCount() {
return data.size();
}
@Override
public Object getItem(int position) {
return data.get(position);
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
if (convertView == null) {
convertView = inflater.inflate(R.layout.list_item_edit, parent, false);
holder = new ViewHolder();
holder.editText = convertView.findViewById(R.id.edit_text);
holder.buttonSave = convertView.findViewById(R.id.button_save);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
holder.editText.setText(data.get(position));
holder.buttonSave.setOnClickListener(v -> {
String newText = holder.editText.getText().toString();
data.set(position, newText);
notifyDataSetChanged();
});
return convertView;
}
static class ViewHolder {
EditText editText;
Button buttonSave;
}
}
MainActivity
中:public class MainActivity extends AppCompatActivity {
private ListView listView;
private EditableListAdapter adapter;
private List<String> data;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
listView = findViewById(R.id.list_view);
// 初始化數據
data = new ArrayList<>();
data.add("Item 1");
data.add("Item 2");
data.add("Item 3");
// 設置適配器
adapter = new EditableListAdapter(this, data);
listView.setAdapter(adapter);
}
}
activity_main.xml
中:<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<ListView
android:id="@+id/list_view"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
</LinearLayout>
現在,當你運行應用程序時,你應該可以看到一個包含可編輯項的ListView。用戶可以在EditText中輸入新文本,然后點擊“Save”按鈕來保存更改。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。