0

I'm still new to Android Studio, and for practice I want to make a simple To-Do list app. I'm troubles with creating a new TextView and displaying it.

I know that I probably need to manually insert the TextView into the layout, but I have no idea how to do that.

Here's my MainActivity code:

public class MainActivity extends AppCompatActivity implements View.OnClickListener {

    Button submitBtn;
    EditText userInput;

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

        submitBtn = (Button)findViewById(R.id.submitBtn);
        userInput = (EditText)findViewById(R.id.userInput);

        submitBtn.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        if(v.getId() == R.id.submitBtn) {
            String userInputString = userInput.getText().toString();
            TextView listItem = new TextView(this);
            listItem.setText(userInputString);
        }
    }
}

I am using ConstraintLayout for my layouting. If somebody could help guide me to the right direction, that would be greatly appreciated, thanks in advance!

Gabriel Gavrilov
  • 337
  • 3
  • 11
  • Does this answer your question? [How to Programmatically Add Views to Views](https://stackoverflow.com/questions/2395769/how-to-programmatically-add-views-to-views) – Quadslab Jun 06 '21 at 17:26

1 Answers1

1

In the simplest case, you get your ConstraintLayout using its ID and then call addView(View) with your TextView as the parameter on it. Assuming your ConstraintLayout has the id myLayout:

ConstraintLayout layout = (ConstraintLayout)findViewById(R.id.myLayout);
layout.addView(listItem);
Quadslab
  • 294
  • 3
  • 9