[Android] using code to build Android view Components

Source: Internet
Author: User

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.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.