Android - Add textview to layout when button is pressed

后端 未结 1 1303
悲哀的现实
悲哀的现实 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:

    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:id="@+id/linearLayout">
     <EditText 
        android:id="@+id/editText"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
     />
    <Button 
        android:id="@+id/button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Add+"
    />
    

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