A Button is one of the most widely used components in android. a Button can be configured in XML or directly used in a program, is a Button, which is one of the most widely used components in android. a Button can be configured in XML, or directly used in a program.
In the XML layout file, the following units are encountered:
Px: the pixel of the screen.
In: Inches
Mm: mm
Pt: LB, 1/72 inch
Dp: an abstract unit based on density. if a screen of DPI is displayed, 1dp = 1px.
Dip: equivalent to dp
Sp: Similar to dp, but it also scales according to the user's font size preference.
We recommend that you use sp as the unit of text, and dip for others.
Example 1: layout in XML, which makes it easier to modify the control later and conforms to the MVC mode.
Main. xml layout file
TestButton. java source code
Package org. loulijun. button; import android. app. activity; import android. OS. bundle; import android. view. gravity; import android. view. view; import android. widget. button; import android. widget. toast; public class TestButton extends Activity {/** Called when the activity is first created. */private Button btn1, btn2; @ Override public void onCreate (Bundle savedInstanceState) {super. onCreate (savedInstanceState); setContentView (R. layout. main); btn1 = (Button) findViewById (R. id. button1); --- obtain the parent control id btn2 = (Button) findViewById (R. id. button2); // Set monitoring for the control. when Button 1 is clicked, a prompt is displayed. when Button 2 is clicked, the program btn1.setOnClickListener (new Button. onClickListener () {@ Override public void onClick (View arg0) {// TODO Auto-generated method stub Toast toast = Toast. makeText (TestButton. this, "you clicked" + btn1.getText (). toString (), Toast. LENGTH_SHORT); toast. setGravity (Gravity. TOP, 0,150); toast. show () ;}}); btn2.setOnClickListener (new Button. onClickListener () {@ Override public void onClick (View v) {// TODO Auto-generated method stub TestButton. this. finish ();}});}}
Running result:
Public class TestButton extends Activity {private Button btn1, btn2; public void onCreate (Bundle savedInstanceState) {super. onCreate (savedInstanceState); setContentView (R. layout. main); btn1 = (Button) findViewById (R. id. button1); btn2 = (Button) findViewById (R. id. button2); btn1.setWidth (150); -- set the button width. of course, you can also use setHeight () to set the height btn2.setWidth (100); btn1.setText ("button 1 "); --- set the button text display information btn2.setText ("Anne two"); btn1.setTextColor (Color. GREEN); --- set the text Color btn2.setTextColor (Color. RED); btn1.setTextSize (30); --- set the text size in the button btn2.setTextSize (20); btn2.setBackgroundColor (Color. RED); --- set the button background color }}
The above is the content of the Android UI control series: Button (Button). For more information, see PHP Chinese network (www.php1.cn )!