0

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
mightyWOZ
  • 7,946
  • 3
  • 29
  • 46
AnxiousDino
  • 187
  • 15

2 Answers2

1

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;
}
Drashti Dobariya
  • 2,455
  • 2
  • 10
  • 23
  • Hi @Saylavie1997 if this or any answer has solved your question please consider [accepting it](https://meta.stackexchange.com/q/5234/179419) by clicking the check-mark. This indicates to the wider community that you've found a solution and gives some reputation to both the answerer and yourself. There is no obligation to do this. – Drashti Dobariya Sep 16 '21 at 07:35
  • 1
    Okay cool, I will do that. I'm still figuring out the functions and features here on stackoverflow :) – AnxiousDino Sep 16 '21 at 11:35
1

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!

JumperBot_
  • 551
  • 1
  • 6
  • 19