Skip to content
Advertisement

How do I create a new TextView and display it? (with programming)

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!

Advertisement

Answer

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);
Advertisement