-6

I have a screen on my app where the user should be able to add reminders, and then toggle them individually with a switch (see screenshot below)

My question is, is there any way I can add/remove textviews and switches from an app screen using Java?

I'm new to app development, so I'm sorry if this is trivial or impossible! Cheers, Oli

Screenshot of app screen

Community
  • 1
  • 1
Oliver Wales
  • 41
  • 1
  • 9

3 Answers3

1

To add a textView within a linear layout:

 LinearLayout ll = (LinearLayout) findViewById(R.id.linearlayout);
 TextView textView= new TextView(this);
 textView.setText("some text"); 
 ll.addView(textView); 

To remove a textView within a linear layout:

LinearLayout ll = (LinearLayout) findViewById(R.id.linearlayout);
TextView tV = (TextView) findViewById(R.id.textView);
ll.removeView(tV);
0

The easiest case for you (in my opinion) would be to add maximum number of those inner layouts (TextView + toggle switch) and use Visibility.GONE/INVISIBLE etc.

If you want to do that dynamically you can use a RecyclerView, and have those ona list, you will have some challenges with handling user input though, but it's not that difficult.

0

For each reminder, inflate the layout containing the TextView and the Switch and add it to your parent layout. E.g. Your parent layout is named layoutReminders:

for (Reminder reminder : reminderList) {
    View reminderView = LayoutInflater.from(this).inflate(
        R.layout.item_reminder, layoutReminders, false);

    TextView textReminder = (TextView) reminderView.findViewById(R.id.textReminder);
    Switch switchReminder = (Switch) reminderView.findViewById(R.id.switchReminder);

    textReminder.setText(reminder.getDescription());
    switchReminder.setChecked(reminder.isChecked());

    switchReminder.setOnCheckedListener(new OnCheckedListener() ...);

    layoutReminder.addView(reminderView);
}

In OnCheckedListener you update reminderList and layout accordingly.

terencey
  • 3,282
  • 4
  • 32
  • 40