Create run-time elements on Android

0

Is it possible to create elements at runtime on Android?

For example, I want to build an app where the user can create a questionnaire or a checklist and save it to the database.

Depending on the issues or items to be scanned, which were created by the user, the application would mount the elements for the user's actions.

Is it possible?

    
asked by anonymous 30.05.2017 / 20:40

2 answers

2

Yes, you can create interface elements at runtime. Something like:

//...
parent.setLayoutParams(new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT));
parent.setOrientation(LinearLayout.HORIZONTAL);

TextView tv = new TextView(context);
parent.addView(tv);
//...

Is it something you're looking for?

    
30.05.2017 / 20:58
3

Yes, it is possible. You can use the addView () method on any ViewGroup like LinearLayout, RelativeLayout, etc. Here is an example:

package com.example.androidview;

import android.os.Bundle;
import android.app.Activity;
import android.widget.Button;
import android.widget.LinearLayout;

public class MainActivity extends Activity {

 @Override
 protected void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.activity_main);

  LinearLayout mainLayout = 
    (LinearLayout)findViewById(R.id.mainlayout);

  //newButton added to the existing layout
  Button newButton = new Button(this);
  newButton.setText("Hello");
  mainLayout.addView(newButton);

  //anotherLayout and anotherButton added 
  //using addContentView()
  LinearLayout anotherLayout = new LinearLayout(this);
  LinearLayout.LayoutParams linearLayoutParams = 
    new LinearLayout.LayoutParams(
      LinearLayout.LayoutParams.WRAP_CONTENT,
      LinearLayout.LayoutParams.WRAP_CONTENT);

  Button anotherButton = new Button(this);
  anotherButton.setText("I'm another button");
  anotherLayout.addView(anotherButton);

  addContentView(anotherLayout, linearLayoutParams);
 }

}

More details here:

link

    
30.05.2017 / 20:58