Home > Back-end >  Add TextView, when button is pushed Kotlin
Add TextView, when button is pushed Kotlin

Time:09-17

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

CodePudding user response:

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

CodePudding user response:

Here, you could just create the TextView and set it's Visibility to INVISIBLE on MainActivity after the onCreate() of the program, then on button click set it to VISIBLE. You could do this infinitely!

  • Related