简体   繁体   中英

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!

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM