実現したいこと
削除ボタンを機能させること
前提
android studioでTodoリストを作成しています
発生している問題・エラーメッセージ
該当のソースコード
Todo.java
package com.example.studytodo; import androidx.appcompat.app.AppCompatActivity; import androidx.fragment.app.FragmentManager; import android.os.Bundle; import android.util.Log; public class Todo extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.todo); FragmentManager fm = getSupportFragmentManager(); fm.setFragmentResultListener(TodoFragment.REQUEST_KEY, this, (rkey,result)->{ // TodoFragment が back したら何する? Log.d("MainActivity", "backed todofragment."); }); fm.beginTransaction() .replace(R.id.fragment_container_view, new TodoFragment()) .commit(); } }
TodoFragment.java
package com.example.studytodo; import androidx.annotation.*; import androidx.fragment.app.*; import androidx.recyclerview.widget.*; import android.content.Intent; import android.os.Bundle; import android.util.Log; import android.view.*; import android.widget.*; import java.io.Serializable; import java.time.LocalDateTime; import java.time.format.DateTimeFormatter; import java.util.*; public class TodoFragment extends Fragment { static final String REQUEST_KEY = "TodoFragment"; private List<Task> taskList = new ArrayList<>(); public TodoFragment() { super(R.layout.fragment_todo); } @Override public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); TaskAdapter taskAdapter = new TaskAdapter(); RecyclerView recyclerView = view.findViewById(R.id.recyclerViewTasks); recyclerView.setAdapter(taskAdapter); FragmentManager fm = getChildFragmentManager(); fm.setFragmentResultListener(AddTaskFragment.REQUEST_KEY, getViewLifecycleOwner(), (rkey, result) -> { taskAdapter.addTask((Task) result.getSerializable(AddTaskFragment.RESULTKEY_TASK)); }); fm.setFragmentResultListener(AddTaskFragment.REQUEST_KEY, getViewLifecycleOwner(), (rkey, result) -> { Task addedTask = (Task) result.getSerializable(AddTaskFragment.RESULTKEY_TASK); // TaskAdapterに追加 taskAdapter.addTask(addedTask); // TodoFragment内のリストにも追加 taskList.add(addedTask); }); ImageButton btBackTodo = view.findViewById(R.id.btBackTodo); btBackTodo.setOnClickListener(v -> { Toast.makeText(getContext(), "戻るボタンがクリックされました", Toast.LENGTH_SHORT).show(); getParentFragmentManager().setFragmentResult(REQUEST_KEY, new Bundle()); //(MainActivity に)通知 Intent intent = new Intent(requireContext(), MainActivity.class); startActivity(intent); requireActivity().finish(); }); ImageButton addButton = view.findViewById(R.id.btAdd); addButton.setOnClickListener(v -> { Toast.makeText(getContext(), "追加ボタンがクリックされました", Toast.LENGTH_SHORT).show(); new AddTaskFragment().show(fm, null); //ダイアログ表示 }); } } class TaskAdapter extends RecyclerView.Adapter<TaskAdapter.ViewHolder> { private final List<Task> taskList = new ArrayList<>(); void addTask(Task task) { Log.d("TaskAdded", "Task added: " + task); taskList.add(task); notifyItemInserted(taskList.size()-1); } void removeTask(int position) { taskList.remove(position); notifyItemRemoved(position); notifyItemRangeChanged(position, taskList.size()); } @NonNull @Override public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) { return new ViewHolder(parent); } @Override public void onBindViewHolder(@NonNull ViewHolder holder, int position) { Log.d("AdapterDebug", "onBindViewHolder called for position: " + position); holder.bind(taskList.get(position)); } @Override public int getItemCount() { return taskList.size(); } static class ViewHolder extends RecyclerView.ViewHolder { private final TextView taskName, dateTime; public ViewHolder(@NonNull ViewGroup parent) { super(LayoutInflater.from(parent.getContext()).inflate(R.layout.task_item, parent, false)); taskName = itemView.findViewById(R.id.taskNameTextView); dateTime = itemView.findViewById(R.id.dateTimeTextView); } void bind(Task task) { taskName.setText(task.taskName); dateTime.setText(task.getDateTime()); } } } class Task implements Serializable { static final DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy/MM/dd HH:mm"); final String taskName; final LocalDateTime dateTime; public Task(String taskName, LocalDateTime dateTime) { this.taskName = taskName; this.dateTime = dateTime; } String getDateTime() { return formatter.format(dateTime); } @Override public String toString() { return taskName + " at " + getDateTime(); } }
TodoViewModel.java
package com.example.studytodo; import androidx.lifecycle.ViewModel; import androidx.lifecycle.MutableLiveData; public class TodoViewModel extends ViewModel { private MutableLiveData<Task> addedTask = new MutableLiveData<>(); public void setAddedTask(Task task) { addedTask.setValue(task); } public MutableLiveData<Task> getAddedTask() { return addedTask; } }
AddTaskFragment.java
package com.example.studytodo; import androidx.annotation.*; import androidx.appcompat.app.AlertDialog; import androidx.fragment.app.DialogFragment; import android.app.*; import android.os.Bundle; import android.view.*; import android.widget.*; import java.time.*; public class AddTaskFragment extends DialogFragment { static final String REQUEST_KEY = "AddTaskFragment"; static final String RESULTKEY_TASK = "task"; private EditText nameView, datetimeView; private LocalDateTime datetime; @NonNull @Override public Dialog onCreateDialog(@Nullable Bundle savedInstanceState) { View view = LayoutInflater.from(requireContext()).inflate(R.layout.fragment_add_task, null); datetime = LocalDateTime.now(); nameView = view.findViewById(R.id.editTextTaskName); datetimeView = view.findViewById(R.id.editTextDateTime); datetimeView.setOnClickListener(v -> showDatePickerDialog()); return new AlertDialog.Builder(requireContext()) .setTitle("Add Task") .setView(view) .setPositiveButton("保存", (d, w) -> { String name = nameView.getText().toString(); Bundle result = new Bundle(); result.putSerializable(RESULTKEY_TASK, new Task(name, datetime)); getParentFragmentManager().setFragmentResult(REQUEST_KEY, result); dismiss(); }) .setNegativeButton("キャンセル", (d, w) -> dismiss()) .create(); } private void showDatePickerDialog() { DatePickerDialog datePickerDialog = new DatePickerDialog(getContext(), (v, y, m, d) -> { //m: 0-11 datetime = datetime.with(LocalDate.of(y, m+1, d)); //m: 1-12 showTimePickerDialog(); }, datetime.getYear(), datetime.getMonthValue()-1, datetime.getDayOfMonth()); //m: 0-11 datePickerDialog.show(); } private void showTimePickerDialog() { TimePickerDialog timePickerDialog = new TimePickerDialog(getContext(), (v, h, m) -> { datetime = datetime.with(LocalTime.of(h, m)); datetimeView.setText(Task.formatter.format(datetime)); }, datetime.getHour(), datetime.getMinute(), true); timePickerDialog.show(); } }
試したこと
removeTaskなどを追加して削除ができるのかやってみたのですが、うまくいきません。
別の方法を試した方がいいのでしょうか?
補足情報(FW/ツールのバージョンなど)
android studio
0 コメント