Android - Add textview to layout when button is pressed

后端 未结 1 1315
悲哀的现实
悲哀的现实 2020-11-29 02:14

So right now I have a text field with a button (add+) below it.

I would like to make it so every time text is entered into the Text Field, and the Add button is pres

1条回答
  •  遥遥无期
    2020-11-29 03:15

    This code contains what you want. (The view show an EditText and a Button, after you click on the button the text will add to the LinearLayout)

        private LinearLayout mLayout;
    private EditText mEditText;
    private Button mButton;
    
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        mLayout = (LinearLayout) findViewById(R.id.linearLayout);
        mEditText = (EditText) findViewById(R.id.editText);
        mButton = (Button) findViewById(R.id.button);
        mButton.setOnClickListener(onClick());
        TextView textView = new TextView(this);
        textView.setText("New text");
    }
    
    private OnClickListener onClick() {
        return new OnClickListener() {
    
            @Override
            public void onClick(View v) {
                mLayout.addView(createNewTextView(mEditText.getText().toString()));
            }
        };
    }
    
    private TextView createNewTextView(String text) {
        final LayoutParams lparams = new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
        final TextView textView = new TextView(this);
        textView.setLayoutParams(lparams);
        textView.setText("New text: " + text);
        return textView;
    }
    

    And the xml is:

    
     
    

    0 讨论(0)
提交回复
热议问题