In the last article, we made a simple todo app, but there’s nothing more than just add tasks to the list without checking for completing. This post, we’ll make the custom layout for every single item in the list, provide the button the check for completion.

Watch the full video here:

There are 3 steps we need to do.

Create custom Layout

Create a layout with a textview to display the text of the task, and a button so that user can tap for checking the task completion.

Create a custom Adapter class: TodoAdapter

Instead of using the default adapter and default layout from android, we’ll make our own Adapter for using the custom layout that we made.

This adapter needs an arraylist to contain the list of tasks, and an Layout Inflator object to inflate the layout.

This class must be extended from BaseAdapter superclass, hence, we have to implement the abstract methods and override them.

We modify the component inside the getView method and return the view.


public class TodoAdapter extends BaseAdapter {
private ArrayList todoList;
private LayoutInflater inflater;

public TodoAdapter(ArrayList todoList, Context context) {
this.todoList = todoList;
this.inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}

@Override
public int getCount() {
return todoList.size();
}

@Override
public Object getItem(int position) {
return todoList.get(position);
}

@Override
public long getItemId(int position) {
return position;
}

@Override
public View getView(int position, View convertView, ViewGroup parent) {
View view = inflater.inflate(R.layout.todo_detail, null);
TextView todoText = view.findViewById(R.id.todoText);
Button completeButton = view.findViewById(R.id.completeButton);

completeButton.setText("Incompleted");
todoText.setText(todoList.get(position).toString());

return view;
}
}

Set adapter for the ListView

The last thing we need to do to make use of the custom layout is setAdapter for the listview using the TodoAdapter in MainActivity class


public class MainActivity extends AppCompatActivity {

Button addButton;
EditText inputText;
ListView todoList;
ArrayList<String> list;
TodoAdapter todoAdapter;

public void onAddItem(View view){
String text = inputText.getText().toString();

if(!text.equals("")){

list.add(text);

todoList.setAdapter(todoAdapter);

inputText.setText("");
}
}

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);


addButton = findViewById(R.id.addButton);
inputText = findViewById(R.id.inputField);
todoList = findViewById(R.id.todoListView);
list = new ArrayList<>();

todoAdapter= new TodoAdapter(list, this);

}
}

LEAVE A REPLY

Please enter your comment!
Please enter your name here