Search code examples
androidkotlinbuttontextviewandroid-linearlayout

Add TextView, when button is pushed Kotlin


I don't understand why it isn't just as simple as this...

       // Add field
    val LineLayoutInfo = findViewById<View>(R.id.LineLayoutInfo) as LinearLayout
    val Add_Field = findViewById<View>(R.id.buttonAddField) as Button
    Add_Field.setOnClickListener{

        val tv1 = TextView(this@MainActivity)
        tv1.text = "Show Up"
        val t = TextView(applicationContext)

        LineLayoutInfo.addView(tv1)
    }

All I want to do is create a new TextView inside my current LinearLayout. This part of the code is written in Kotlin and stored in the OnCreate(). Is it maybe because I need to refresh the activity?

The output I get when I push the button, looks like this.

D/HwAppInnerBoostImpl: asyncReportData com.xxx.httpposter,2,1,1,0 interval=83
I/ViewRootImpl: jank_removeInvalidNode all the node in jank list is out of time
V/AudioManager: playSoundEffect   effectType: 0
V/AudioManager: querySoundEffectsEnabled...
D/HwAppInnerBoostImpl: asyncReportData com.xxx.httpposter,2,1,2,0 interval=353

Solution

  • You can try something like this

    private LinearLayout mLayout;
    private Button mButton;
    
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        mLayout = (LinearLayout) findViewById(R.id.linearLayout);
        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("New Text"));
            }
        };
    }
    
    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;
    }