Generally, when creating an android view, we directly edit the XML file using a tool.
Set setcontentview (R. layout. Main) in oncreate; create a view directly.
It's just my personal habit. I still like to get these things through code.
So today I learned how to directly use the code to create an android view and add controls.
First, let's take a look at these graphs. The activity has only one setcontentview function. It can be inferred that the activity has only one view Member.
Viewgroup can be placed into a set of multiple views. Therefore, if we want to create a view, the first layer of the activity must be viewgroup or its subclass.
Therefore, we can only use viewgroup to create custom composite view controls.
Sample Code:
public class LEDTestActivity extends Activity {LinearLayout m_layout;private Button m_btnOn;private Button m_btnOff; /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); //setContentView(R.layout.main); m_layout = new LinearLayout(this);m_btnOn = new Button(this);m_btnOn.setText("ON");m_btnOn.setWidth(300);m_btnOff = new Button(this);m_btnOff.setText("OFF");m_btnOff.setWidth(300);m_btnOn.setOnClickListener(new Button.OnClickListener(){public void onClick(View v) {// TODO Auto-generated method stub }});m_btnOff.setOnClickListener(new Button.OnClickListener(){public void onClick(View v) {// TODO Auto-generated method stub }});m_layout.setHorizontalFadingEdgeEnabled(false);m_layout.setVerticalFadingEdgeEnabled(true);m_layout.addView(m_btnOff);m_layout.addView(m_btnOn); setContentView(m_layout); }}
In the code, I create linearlayout directly, put the two button components into linearlayout, and call activity setcontentview to m_layout.
In this way, the simplest example is achieved.