Create elements at runtime on Android

Asked

Viewed 840 times

0

You can create elements at runtime on Android?

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

Depending on the questions or items to be checked, which were created by the user, the application would assemble the elements for the user’s actions.

It is possible?

2 answers

3

Yes, it is possible. You can use the addView() method in any Viewgroup as Linearlayout, Relativelayout, etc. Follow 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:

http://android-coding.blogspot.com.br/2013/10/add-view-programmatically-using-addview.html

  • Marcio, could you add a piece of code here in Stackoverflow? Because it will break, and over time we would not have the information

  • I edited my answer

  • Thanks for the help. I’ll test and come back to comment.

2


Yes, it is possible to 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);
//...

It’s something you’re looking for?

  • Thanks for your help. My idea is based on something similar to joomla, where you can create elements (comboboxes, check, radiogroup, etc.) and the specifications are saved in the database, just read this information and create the screen elements for the user. I’ll test the codes and come back to comment.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.