0

I am an iOS Swift developer learning to make Android apps. I was wondering if there is an equivalent way to dynamically / programmatically create UI objects in Android. In iOS I can simply

let btn = UIButton() // Create a UI object
btn.frame = CGRect(x: 0, y: 0, width: 100, height: 100) // Set the frame of the object
btn.backgroundColor = UIColor.blue // Mess with the properties of the object
self.view.addSubview(btn) // Add it to a UIView

In Android it seems like I always need to have an XML version of the object. Also I can't seem to easily set the object's frame? I really like doing this programatically because my UI is quite intricate and I like using precise pixel based calculations for positioning. Is there no equivalent to this from Java?

Anters Bear
  • 1,816
  • 1
  • 15
  • 41
  • Its not really the greatest of ideas to do UI stuff programatically as it significantly increases the amount of code but it can be done and here is a quick example https://stackoverflow.com/questions/3204852/android-add-a-textview-to-linear-layout-programmatically – tyczj Jun 18 '19 at 14:18
  • Any reason why you dont want to just use xml layouts? – tyczj Jun 18 '19 at 14:33
  • I would kindly disagree here. I think creating UI programmatically within your app and not using XML has a lot of benefits. For one, not inflating XML in different layouts significantly reduces drawing/rendering performance. Secondly, not having XML in your project can reduce your APK or App Bundle size by a decent amount. Finally, being able to encapsulate logic that can manipulate those programmatic UI's makes your code a lot cleaner and a lot more flexible. – Calvin Rai Mar 05 '21 at 20:44

3 Answers3

1

You can create ui objects dynamically. Like:

Button btn = new Button(context);
btn.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT));

and add it to the layout like:

layout.add(btn);

Remember that if you don't have context then you can't create ui objects.

If you know how to put your ui object in xml you will quickly learn other things in dynamic creating )

Axbor Axrorov
  • 2,720
  • 2
  • 17
  • 35
1

You can create objects from code, but it is not very advisable. The final code is MUCH clearer and interpretable if it is represented in the xml file. If you want to insert a buttom from code:

Button actionBtn = new Button(this); // Create a UI object
actionBtn.setLayoutParams(new ViewGroup.LayoutParams(
            ViewGroup.LayoutParams.WRAP_CONTENT,
            ViewGroup.LayoutParams.WRAP_CONTENT)); // Set the frame of the object

actionBtn.setBackgroundColor(getResources().getColor(R.color.blue)); // Mess with the properties of the object
setContentView(actionBtn); // Add it to a UIView
  • Hi so I can't really set the frame using pixels? like from my example at (0,0,100,100). So I have to use the layout essentially to position things? – Anters Bear Jun 18 '19 at 14:20
  • In Android you should design for many differents devices, so is not good idea use hard-coded pixel values. However, you can try something like actionBtn .getLayoutParams().height=180; – Salvador Nasser Jun 18 '19 at 14:28
1

Yes! You absolutely can! In fact, creating views and UI programmatically has a lot of great benefits in Android:

  1. Since you're not inflating and using XML files, rendering performance becomes a lot faster and more performant, especially for more complicated UI.
  2. Your views and UI can now be a lot more flexible and reusable, especially when you need to change UI dynamically at runtime.
  3. You can store a lot of binding and manipulation logic right into a custom view class, so you can do things like myCustomView.updateLabel("new label") without having to do stuff like findViewById(...)
  4. You can encapsulate your programmatic UI into reusable classes, like the one shown below:
class MyCustomView : FrameLayout {

    constructor(context: Context) : super(context)
    constructor(context: Context, attrs: AttributeSet) : super(context, attrs)
    constructor(context: Context, attrs: AttributeSet, defStyleAttr: Int) : super(
        context, attrs, defStyleAttr
    )

    init {
        val button = Button(context)
        val buttonParams = LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT)
        buttonParams.gravity = Gravity.CENTER
        button.text = "Click Me!"
        button.layoutParams = buttonParams
        this.addView(button)
    }
}

This class creates a FrameLayout that has a button with some text on it, centered vertically and horizontally within the FrameLayout.

Although programmatic UI is incredible, you should really use the tool that works best for your use case. If you're creating a UI that will be used in many places in your app, consider doing this programmatically via a custom View class, like the one shown above. If you're just making a one-off UI that is relatively simple and doesn't have a lot of nested layouts, then XML is far quicker and easier.

Dharman
  • 30,962
  • 25
  • 85
  • 135
Calvin Rai
  • 816
  • 1
  • 8
  • 17