Android - creating UI via Code
We have seen already some examples of using xml layout files to specify GUI elements and how to attach them to variables in the code.
What if we want to completely generate the UI not in xml but in code, this shows an example how to do.
STEP 1: Create in code the GUI component
Basically, for every <GUIELEMEN> we have a class GUIELEMENT
- <LinearLayout > GOES TO LinearyLayout ll = new LinearLayout(); // have series of methods for attributes ll.setOrientation(*)
- <Button> GOES TO Button b = new Button();
STEP 2: Add GUI components to the Activity
- From in Activity class:
- this.addContentView(ll, llParams);
An Example
UICodeActivity.java package net.learn2develop.UICode; import android.app.Activity; import android.os.Bundle; import android.view.ViewGroup.LayoutParams; import android.widget.Button; import android.widget.LinearLayout; import android.widget.TextView; public class UICodeActivity extends Activity { /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); //setContentView(R.layout.main); //---param for views--- LayoutParams params = new LinearLayout.LayoutParams( LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT); //---create a layout--- LinearLayout layout = new LinearLayout(this); layout.setOrientation(LinearLayout.VERTICAL); //---create a textview--- TextView tv = new TextView(this); tv.setText("This is a TextView"); tv.setLayoutParams(params); //---create a button--- Button btn = new Button(this); btn.setText("This is a Button"); btn.setLayoutParams(params); //---adds the textview--- layout.addView(tv); //---adds the button--- layout.addView(btn); //---create a layout param for the layout--- LinearLayout.LayoutParams layoutParam = new LinearLayout.LayoutParams( LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT ); this.addContentView(layout, layoutParam); } } |