- // src/main/java/com/example/todolist/MainActivity.java
- package com.example.todolist;
- import android.app.AlertDialog;
- import android.content.DialogInterface;
- import android.os.Bundle;
- import android.view.View;
- import android.widget.AdapterView;
- import android.widget.ArrayAdapter;
- import android.widget.Button;
- import android.widget.EditText;
- import android.widget.ListView;
- import androidx.appcompat.app.AppCompatActivity;
- import java.util.ArrayList;
- public class MainActivity extends AppCompatActivity {
- private ArrayList<String> tasks;
- private ArrayAdapter<String> adapter;
- private ListView taskListView;
- private EditText taskInput;
- private Button addButton, editButton, deleteButton;
- private int selectedTaskPosition = -1;
- @Override
- protected void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.activity_main);
- taskInput = findViewById(R.id.taskInput);
- addButton = findViewById(R.id.addButton);
- editButton = findViewById(R.id.editButton);
- deleteButton = findViewById(R.id.deleteButton);
- taskListView = findViewById(R.id.taskList);
- tasks = new ArrayList<>();
- adapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_single_choice, tasks);
- taskListView.setAdapter(adapter);
- taskListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
- @Override
- public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
- selectedTaskPosition = position;
- taskInput.setText(tasks.get(position));
- }
- });
- addButton.setOnClickListener(new View.OnClickListener() {
- @Override
- public void onClick(View v) {
- String task = taskInput.getText().toString();
- if (!task.isEmpty()) {
- if (selectedTaskPosition >= 0) {
- tasks.set(selectedTaskPosition, task);
- selectedTaskPosition = -1;
- } else {
- tasks.add(task);
- }
- adapter.notifyDataSetChanged();
- taskInput.setText("");
- }
- }
- });
- editButton.setOnClickListener(new View.OnClickListener() {
- @Override
- public void onClick(View v) {
- if (selectedTaskPosition >= 0) {
- String newTask = taskInput.getText().toString();
- if (!newTask.isEmpty()) {
- tasks.set(selectedTaskPosition, newTask);
- adapter.notifyDataSetChanged();
- taskInput.setText("");
- selectedTaskPosition = -1;
- }
- }
- }
- });
- deleteButton.setOnClickListener(new View.OnClickListener() {
- @Override
- public void onClick(View v) {
- if (selectedTaskPosition >= 0) {
- new AlertDialog.Builder(MainActivity.this)
- .setTitle("Delete Task")
- .setMessage("Are you sure you want to delete this task?")
- .setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
- public void onClick(DialogInterface dialog, int which) {
- tasks.remove(selectedTaskPosition);
- adapter.notifyDataSetChanged();
- taskInput.setText("");
- selectedTaskPosition = -1;
- }
- })
- .setNegativeButton(android.R.string.no, null)
- .show();
- }
- }
- });
- }
- }