alex_bn_lee

导航

【063】◀▶ Android (I) - 控件和布局

●·● 目录:

package: android.widget

  Android UI controls  

A½ ………… View 类
A1 ………… TextView 类
A2 ………… Button 类
A3 ………… EditText 类
A4 ………… RadioGroup 类
A5 ………… RadioButton 类
A6 ………… CheckBox 类
A7 ………… ProgressBar 类
A8 ………… ListView 类
        ExpandableListView 类
A9 ………… Spinner 类
Aa ………… SeekBar 类
Ab ………… RatingBar 类
Ac ………… ImageView 类
Ad ………… Toast 类
Ae ………… WebView 类
Af  ………… ToggleButton 类
Ag ………… AutoCompleteTextView 类
Ah ………… TimePicker 类

  Android layout controls  

D1 ………… FrameLayout 类
D1¼ ………… ScrollView 类
D1½ ………… HorizontalScrollView 类
D2 ………… LinearLayout 类
D3 ………… RelativeLayout 类
D4 ………… GridView 类
D6 ………… TableLayout 类
D7 ………… TableRow 类

---------------------------------------------------------------------------------------------------------

            ╔═════════╗
╠════╣     第A½个    ╠══════════════════════════════════════════════════╣
            ╚═════════╝

●·● View 类

1. 其它控件的基类,此类具有的方法属性,继承自它的类就都有。

2. View XML Attributes:

  • android:focusable:控件在默认情况下是是不能获取焦点的, 只有设置为 true 后才可以. 例如 EditText 是默认可以获取焦点的, 若是不想运行程序后立刻被 EditView 获取焦点, 则可以对 LinearLayout 或是 RelativeLayout 设置此属性为 true.
  • android:focusableInTouchMode:可以通过touch来获得focus(true).

  


 

---------------------------------------------------------------------------------------------------------

            ╔════════╗
╠════╣    第A1个    ╠══════════════════════════════════════════════════╣
            ╚════════╝

●·● TextView 类

1. 文字显示, 类似标签.

2. TextView XML Attributes:

  • android:autoLink:超链接. (none, web, email, phone, map, all)
  • android:ellipsize:省略号位置. (none, start, middle, end, marquee)
  • android:id:唯一标识符.
  • android:text:显示的文本内容.
  • android:textSize:文本字体大小. (单位 sp)
  • android:background:背景颜色.
  • android:singleLine:将控件中的所有内容是否显示在一行中.

  • android:layout_width:布局宽度.
  • android:layout_height:布局高度.
  • android:layout_weigh:线性布局控件大小所占的比重.

  • android:gravity:对齐, 控件内部文本的对齐方式. 对于 LinearLayout 来说, 则是其内部的控件的对齐方式.
  • android:layout_gravity:控件本身在父控件中的对齐方式.
    ※ 参考:Android中gravity与layout_gravity的区别

  • android:paddingLeft:左边的填充宽度. (单位 dip)【内边距】
  • android:paddingTop:上边的填充宽度.
  • android:paddingRight:右边的填充宽度.
  • android:paddingBottom:下边的填充宽度.
  • android:padding:上下左右四边的填充宽度.

  • android:marginLeft:左边缘宽度.【外边距】
  • android:marginTop:上边缘宽度.
  • android:marginRight:右边缘宽度.
  • android:marginBottom:下边缘宽度.
  • android:margin:上下左右四个边缘宽度.

3. TextView Methods:

  • setTypeface(Typeface tf):Style (bold, italic, bolditalic) for the text.
      Typeface.BOLD
      Typeface.BOLD_ITALIC
      Typeface.ITALIC
      Typeface.NORMAL

  • setTextColor(int):通过 Color 类的方法和常量来赋值.
  • setbackground(int):通过 Color 类的方法和常量来赋值.
  • getWidth():返回值:final int. 返回控件的宽度. (像素值)
  • getHeight():返回值:final int. 返回控件的高度.

设置字体颜色:

textView.setText(Html.fromHtml("少就看到<font color=red>乐肤洁</font>积分了"));

跑马灯效果:

        android:ellipsize="marquee"
        android:marqueeRepeatLimit="marquee_forever"
        android:singleLine="true"
        android:focusable="true"
        android:focusableInTouchMode="true"

※ 参考:android TextView属性详解

※ 参考:Android的TextView属性XML详解

☀☀☀<< 举例 >>☀☀☀

控件距离单位 - dip & 字体大小单位 - sp 举例:
效果:

实现代码:

    dip & sp
    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:orientation="vertical"
        android:background="#000000"
        android:padding="5dip"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent" >
        
        <TextView 
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:paddingBottom="5dip"
            android:textColor="#00FF00"
            android:text="距离展示:"
            />
        <Button
            android:id="@+id/button1"
            android:layout_width="150dip"
            android:layout_height="50dip"
            android:text="150dip*50dip" />
        
        <Button
            android:id="@+id/button2"
            android:layout_width="250dip"
            android:layout_height="35dip"
            android:text="250dip*35dip" />
        
        <Button
            android:layout_width="match_parent"
            android:layout_height="50dip"
            android:textSize="15sp"
            android:text="textSize=15sp" />
        
        <Button
            android:layout_width="match_parent"
            android:layout_height="50dip"
            android:textSize="20sp"
            android:text="textSize=20sp" />
        
        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textColor="#00FF00"
            android:textSize="25sp"
            android:text="textSize=25sp" />

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textColor="#00FF00"
            android:textSize="30sp"
            android:text="textSize=30sp" />
        
        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textColor="#00FF00"
            android:textSize="40sp"
            android:text="textSize=40sp" />
        
        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textColor="#00FF00"
            android:textSize="50sp"
            android:text="textSize=50sp" />
        
    </LinearLayout>

根据 pixels = dp * (dpi / 160) 对于相同的 dp 来说,dpi 越大,分辨率越高(屏幕显示越精细),相对应的 pixel 就越大,但是显示的宽度不会有太大的变化,从而达到在不同分比率中显示。

---------------------------------------------------------------------------------------------------------

            ╔════════╗
╠════╣    第A2个    ╠══════════════════════════════════════════════════╣
            ╚════════╝

●·● Button 类

1. 按钮.

若是想在其他的方法中调用某个按钮被电击的事件所产生的效果, 可以这样实现:首先要写好 button1 监听类的内容, 然后直接 new 一个监听类, 然后调用内部的 onClick() 方法, 将 button1 传递为参数即可实现. (performClick)

public class showButtonListener implements OnClickListener  //监听类.
{...}
new showButtonListener().onClick(showButton);  //实现 showButton 被点击.

2. Button XML Attributes:

  • android:layout_column:控件在 TableLayout 中指定索引的列中显示.
  • android:onclick:点击事件的名称.
      在 XML 中将 *.java 中的方法名称写入即可, 然后在 *.java 中实现此方法
      → XML:android:onClick="onClick"
      → java:public void onClick(View v) {}  在内部写入想要实现的功能即可将两者关联起来.
        上面方法中的参数 v 就指代此 button 控件.

3. Button Method:

  • performClick():调用该按钮的点击事件, 前提已经有定义.
  • SetOnClickListener(View.OnClickListener l):设置点击按钮的监听器.
    实现按钮点击
public class Handler_Exer extends Activity {
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_handler__exer);

        Button buttonStart = (Button)findViewById(R.id.button01);  //获取开始按钮
        buttonStart.setOnClickListener(new StartButtonListener());  //设置开始按钮的点击事件
    }
    
    class StartButtonListener implements OnClickListener{  //此类的 onClick 方法中写入要实现的功能, 实现 OnClickListener 接口
        public void onClick(View v) {
            // TODO Auto-generated method stub
            system.out.println("Start");          //点击开始按钮实现的功能
        }
    }
}

---------------------------------------------------------------------------------------------------------

            ╔═════════╗
╠════╣    第A2½个   ╠══════════════════════════════════════════════════╣
            ╚═════════╝

●·● ImageButton 类

1. 图片按钮.

2. ImageButton XML Attributes:

  • android:src:用来设置显示图片的.  → setImageResource(int)
  • android:alpha:0 完全透明, 1 弯曲不透明  → setAlpha(float)

---------------------------------------------------------------------------------------------------------

            ╔════════╗
╠════╣    第A3个    ╠══════════════════════════════════════════════════╣
            ╚════════╝

●·● EditText 类

1. 文本框.

2. EditText XML Attributes:

  • android:hint="请输入数字!"//设置显示在空间上的提示信息
  • android:editable="true"//设置是否可以编辑
  • android:ellipsize:文字满了用省略号代替.(none, start, middle, end, marquee)
  • android:inputType:输入类型.(none, text...)
  • android:numeric="integer"//设置只能输入整数,如果是小数则是:decimal,正负数是:signed,交叉的话用"|"隔开即可.
  • android:singleLine="true"//设置单行输入,一旦设置为true,则文字不会自动换行。
  • android:password="true"//设置只能输入密码
  • android:textColor = "#ff8c00"//字体颜色
  • android:textStyle="bold"//字体,bold, italic, bolditalic
  • android:textSize="20dip"//大小
  • android:capitalize = "characters"//以大写字母写, none, sentences(句子第一个字母大写), words(单词第一个字母大写), characters(每个字母都大写)
  • android:textAlign="center"//EditText没有这个属性,但TextView有,居中
  • android:textColorHighlight="#cccccc"//被选中文字的底色.
  • android:textColorHint="#ffff00"//设置提示信息文字的颜色,默认为灰色
  • android:textScaleX="1.5"//字符的大小在 X 方向上的缩放, 大于一变宽, 小于一变窄.
  • android:typeface="monospace"//字型,normal(常规), sans(与常规很想), serif(类似宋体), monospace(比较细长的等线体)
  • android:background="@null"//背景,这里没有,指透明
  • android:layout_weight="1"//权重,控制控件之间的地位,在控制控件显示的大小时蛮有用的。
  • android:layout_gravity="center_vertical"//设置控件显示的位置:默认top,这里居中显示.

  • android:minWidth:控件最小宽度.
  • android:maxWidth
  • android:minHeight:控件最小高度.
  • android:maxHeight
  • android:maxLength:最大输入长度
  • android:minLines:最少行数.
  • android:maxLines

  • android:drawableLeft:在编辑框左侧显示图片.
  • android:drawableRight:在编辑框右侧显示图片.

3. EditText Methods:

  • setOnFocusChangeListener(OnFocusChangeListener l):EditView 的焦点发生变化的时候触发.
      里面方法:onFocusChange(View v, boolean hasFocus), v 是此控件, hasFocus 返回是否聚焦.

※ 参考:Android开发EditText属性

※ 参考:android中的ellipsize

---------------------------------------------------------------------------------------------------------

            ╔════════╗
╠════╣    第A4个    ╠══════════════════════════════════════════════════╣
            ╚════════╝

●·● RadioGroup 类

1. 一个 RadioButton 的组.

2. RadioGroup XML Attributes:

  • android:checkedButton:="@+id/radiobutton1", 注意有"+"号, 默认选中的单选按钮.
      → getCheckedRadioButtonId()
  • android:orientation:horizontal & vertical.  → setOrientation(int)

3. RadioGroup Methods:

  • setOnCheckedChangeListener(RadioGroup.OnCheckedChangeListener lister):设置单选按钮点击的监听器.

  • check(int id):Sets the selection to the radio button whose identifier is passed in parameter.
  • clearCheck():Clears the selection.
  • CheckedRadioButtonId():Returns the identifier of the selected radio button in this group.

---------------------------------------------------------------------------------------------------------

            ╔════════╗
╠════╣    第A5个    ╠══════════════════════════════════════════════════╣
            ╚════════╝

●·● RadioButton 类

1. 单选按钮.

2. RadioButton XML Attributes:

  • android:checked:是否选中.

3. RadioButton Methods:

  • getId():返回值:int. Returns this view's identifier.
  • isChecked():返回值:boolean.
  • setChecked(boolean checked):Change the checked state of the view.
  • toggle():Change the checked state of the view to the inverse of its current state.

※ 参考:Android---RadioButton(单选按钮)详解

---------------------------------------------------------------------------------------------------------

            ╔════════╗
╠════╣    第A6个    ╠══════════════════════════════════════════════════╣
            ╚════════╝

●·● CheckBox 类

1. 复选框.

<CheckBox android:id="@+id/star"
    style="?android:attr/starStyle"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content" 
    android:text="Star" />

    

通过点击五角星, 以颜色来区分是否选中!

2. CheckBox Methods:

  • setOnClickListener(View.OnClickListener l):被点击的时候触发.
  • setOnCheckedChangeListener(CompoundButton.OnCheckedChangeListener listener):当复选框的选择状态发生变化的时候触发.

  • getId():返回值:int. Returns this view's identifier.
  • isChecked():返回值:boolean.
  • setChecked(boolean checked):Change the checked state of the view.
  • toggle():Change the checked state of the view to the inverse of its current state.

---------------------------------------------------------------------------------------------------------

            ╔════════╗
╠════╣    第A7个    ╠══════════════════════════════════════════════════╣
            ╚════════╝

●·● ProgressBar 类

1. Visual indicator of progress in some operation.

2. ProgressBar XML Attributes:

  • android:progress:定义一个默认的进度值,0和最大值之间的值.
  • android:secondaryprogress
  • android:visibility:定义进度条的可见性. (visible(可见), invisible, gone(完全不可见))
      invisible 只是隐藏, 控件的空间还是存在的, 只是隐藏罢了, gone 则是完全没了, 空间也不在了!
  • android:max:定义进度条的最大值.
  • style="?android:attr/progressBarStyleLarge"  //大圆圈
  • style="?android:attr/progressBarStyleSmall"  //小圆圈
  • style="?android:attr/progressBarStyleHorizontal"  //水平进度条

3. ProgressBar Methods:

  • getMax():返回值:int. 返回进度条范围的最大值.
  • getProgress():返回值:int. 获取进度条的当前进度.
  • getSecondaryProgress():返回值:int. 获取第二进度条的当前进度.
  • incrementProgressBy(int diff):给进度条增加指定数量的进度.
  • incrementSecondaryProgressBy(int diff):给第二进度条增加指定数量的进度.
  • setMax(int max):给进度条设置最大值.
  • setProgress(int progress):给进度条设置进度.
  • setSecondaryProgress(int secondaryProgress):给第二进度条设置进度.
  • setVisibility(int v)设置进度条的可见性. (View.VISIBLE, INVISIBLE, GONE)

※ 参考:Android进度条(ProgressBar)应用实例

---------------------------------------------------------------------------------------------------------

            ╔════════╗
╠════╣    第A8个    ╠══════════════════════════════════════════════════╣
            ╚════════╝

●·● ListView 类

1. A view that shows items in a vertically scrolling list.

2. ListView Constructors:

  • ListView(Context context):

3. ListView XML Attributes:

  • android:drawSelectorOnTop:选中的时候是否覆盖选中项, 一般选择 false.
  • android:scrollbars:滚动条显示方式.

4. ListView Methods:

  • setAdapter(ListAdapter adapter):将数据加到 ListView 内部.

●·● ExpandableListView 类

※ 参考:【068】 Android ListView & ExpandableListView

public class listAc extends ExpandableListActivity{  //继承与ExpandableListActivity
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
        
        List<Map<String, String>> groups = new ArrayList<Map<String,String>>();  //一级目录数据 "group"
        Map<String, String> mapGroups = new HashMap<String, String>();
        mapGroups.put("group", "Group One");
        groups.add(mapGroups);
        mapGroups = new HashMap<String, String>();
        mapGroups.put("group", "Group Two");
        groups.add(mapGroups);
        
        List<Map<String, String>> child1 = new ArrayList<Map<String,String>>();  //一级目录第一个选项的内容部分 "child"
        Map<String, String> child1Data = new HashMap<String, String>();
        child1Data.put("child", "Child1 One");
        child1.add(child1Data);
        child1Data = new HashMap<String, String>();
        child1Data.put("child", "Child1 Two");
        child1.add(child1Data);
        
        List<Map<String, String>> child2 = new ArrayList<Map<String,String>>();  //一级目录第二个选项的内容部分 "child"
        Map<String, String> child2Data = new HashMap<String, String>();
        child2Data.put("child", "child2 One");
        child2.add(child2Data);
        child2Data = new HashMap<String, String>();
        child2Data.put("child", "child2 Two");
        child2.add(child2Data);
        
        List<List<Map<String, String>>> children = new ArrayList<List<Map<String, String>>>();  //二级目录数据 "child"
        children.add(child1);
        children.add(child2);

        SimpleExpandableListAdapter adapter = new SimpleExpandableListAdapter(
                listAc.this,                       //1. context
                groups,                           //2. 一级目录数据
                R.layout.group,                   //3. 一级布局
                new String[]{"group"},             //4. 一级key
                new int[]{R.id.groupItem},         //5. 一级控件
                children,                           //6. 二级目录数据
                R.layout.child,                     //7. 二级布局
                new String[]{"child"},             //8. 二级key
                new int[]{R.id.childItem});            //9. 二级控件
        
        setListAdapter(adapter);
    }
}

---------------------------------------------------------------------------------------------------------

            ╔════════╗
╠════╣    第A9个    ╠══════════════════════════════════════════════════╣
            ╚════════╝

●·● Spinner 类

1. 下拉列表.

2. Spinner XML Attributes:

  • android:prompt:弹出下拉列表的提示内容.
  • android:spinnerMode:dropdown - 下拉菜单. dialog - 对话框形式.

3. Spinner Methods:

  • getSelectItem():返回值:Object. toString() 方法可以获取 Spinner 所显示的文本.
  • getSelectItemId():返回值:long.
  • getSelectItemPosition():返回值:int.
  • getSelectView():返回值:View.

  • setAdapter(SpinnerAdapter adapter):建立数据连接.
        
    ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_single_choice, presidents);
    ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, presidents);
  • setOnItemClickListener(AdapterView.OnItemClickListener):
      onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3):
  • setOnItemSelectedListener(AdapterView.OnItemSelectedListener):选择.
      onItemSelected(AdapterView<?> arg0, View arg1, int arg2, long arg3):选择后触发, 第三个参数, 条目索引.
      onNothingSelected(AdapterView<?> arg0):
      
  • setPrompt(CharSequence prompt):设置提示
  • getCount():

创建一个 Spinner 的步骤:

  • 在布局文件当中声明:<Spinner>
  • 在 string.xml 当中声明一个数组:<string-array>
  • 创建一个 ArrayAdapter:(默认显示样式 & 下拉菜单中每个 item 的样式)
  • 得到 Spinner 对象, 并设置数据:建立连接 & 提示.

※ 参考:Android Spinner实例

※ 参考:Android Spinner的五个部分

☀☀☀<< 举例 >>☀☀☀

效果:

       

首先在 strings.xml 中加入字符串数组:

    View Code
    <string-array name="planets_array">
        <item>Mercury</item>
        <item>Venus</item>
        <item>Earth</item>
        <item>Mars</item>
        <item>Jupiter</item>
        <item>Saturn</item>
        <item>Uranus</item>
        <item>Neptune</item>
    </string-array>

在 MainActivity.java 中写入如下代码:

    View Code
public class MainActivity extends Activity {public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        
        Spinner spinner = (Spinner) findViewById(R.id.spinnerId);              //查找
        ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this,  //加入数据并建立显示样式
                R.array.planets_array, android.R.layout.simple_spinner_item);
        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);  //下拉列表每一项的样式
        spinner.setAdapter(adapter);                              //建立连接
    }
}

同样可以这样实现, 自己建立 list

    View Code
public class MainActivity extends Activity {
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        List<String> list = new ArrayList<String>();
        list.add("Monday");
        list.add("Tuesday");
        list.add("Wednesday");
        list.add("Thursday");
        list.add("Friday");
        
        Spinner spinner = (Spinner)findViewById(R.id.spinner1);
        ArrayAdapter adapter = new ArrayAdapter(MainActivity.this, android.R.layout.simple_spinner_item, list);  //构造函数中加入
        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);  //定义下拉样式, 默认与上面相同
        spinner.setAdapter(adapter);
    }

效果(右面图示):

代码:

    item.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent" >

    <TextView
        android:id="@+id/textView2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignParentTop="true"
        android:padding="10dip"
        android:text="weekday ------ " />
    
    <TextView
        android:id="@+id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_toRightOf="@id/textView2"
        android:layout_alignBaseline="@id/textView2"
        android:textSize="20sp"
        android:text="Large Text" />

</RelativeLayout>
    MainActivity.java
public class MainActivity extends Activity {
    public List<String> list;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        list = new ArrayList<String>();
        list.add("Monday");
        list.add("Tuesday");
        list.add("Wednesday");
        list.add("Thursday");
        list.add("Friday");
        
        Spinner spinner = (Spinner)findViewById(R.id.spinner1);
        ArrayAdapter adapter = new ArrayAdapter(MainActivity.this, R.layout.item, R.id.textView2, list);
        //adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        spinner.setAdapter(adapter);
        spinner.setPrompt("Choose a day:");
        spinner.setOnItemSelectedListener(new Spinner.OnItemSelectedListener() {

            public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
                Toast.makeText(MainActivity.this, list.get(arg2).toString(), Toast.LENGTH_SHORT).show();
            }
            public void onNothingSelected(AdapterView<?> arg0) {
            }
        });
    }
}

---------------------------------------------------------------------------------------------------------

            ╔════════╗
╠════╣    第Aa个    ╠══════════════════════════════════════════════════╣
            ╚════════╝

●·● Seekbar 类

1. 可以手动拉动的进度条.

2. Seekbar Attributes:

  • setOnSeekBarChangeListener(SeekBar.OnSeekBarChangeListener l):

    View Code
public class MainActivity extends Activity {
    public SeekBar seekBar;
    public TextView textView;
    public TextView textView2;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        
        seekBar = (SeekBar)findViewById(R.id.seekBar1);
        textView = (TextView)findViewById(R.id.textView1);
        textView2 = (TextView)findViewById(R.id.textView2);
        textView.setText("Progress = " + Integer.toString(seekBar.getProgress()));
        textView2.setText("Stop");
        seekBar.setOnSeekBarChangeListener(seekBarChangeListener);
    }

    public OnSeekBarChangeListener seekBarChangeListener = new OnSeekBarChangeListener() {
        public void onStopTrackingTouch(SeekBar seekBar) {
            // TODO Auto-generated method stub
            textView2.setText("Stop");
        }
        public void onStartTrackingTouch(SeekBar seekBar) {
            // TODO Auto-generated method stub
            textView2.setText("Start");
        }
        public void onProgressChanged(SeekBar seekBar, int progress,
                boolean fromUser) {
            // TODO Auto-generated method stub
            textView.setText("Progress = " + Integer.toString(progress));
        }
    };
}

---------------------------------------------------------------------------------------------------------

            ╔════════╗
╠════╣    第Ab个    ╠══════════════════════════════════════════════════╣
            ╚════════╝

●·● RatingBar 类

1. 评分 bar.

2. RatingBar XML Attributes:

  • android:numStars:几颗星.
  • android:stepSize:步距.

    View Code
 1 public class MainActivity extends Activity {
 2     public RatingBar ratingBar;
 3     public TextView textView;public void onCreate(Bundle savedInstanceState) {
 4         super.onCreate(savedInstanceState);
 5         setContentView(R.layout.activity_main);
 6         ratingBar = (RatingBar)findViewById(R.id.ratingBar1);
 7         textView = (TextView)findViewById(R.id.textView1);
 8         textView.setText("Progress = " + Integer.toString(ratingBar.getProgress()));
 9         ratingBar.setOnRatingBarChangeListener(new OnRatingBarChangeListener() {
10             public void onRatingChanged(RatingBar ratingBar, float rating,
11                     boolean fromUser) {
12                 // TODO Auto-generated method stub
13                 textView.setText("Progress = " + Integer.toString(ratingBar.getProgress()));
14             }
15         });
16     }
17 }

---------------------------------------------------------------------------------------------------------

            ╔════════╗
╠════╣    第Ac个    ╠══════════════════════════════════════════════════╣
            ╚════════╝

●·● ImageView 类

1. 图片显示控件. 

2. ImageView XML Attributes:

  • android:scaleType:图片的缩放样式.
  • android:src:图片地址.
  • android:alpha:0 和 1 之间的一个数, 表示透明度.
  • android:clickable:是否可以点击.

3. ImageView Methods:

  • startAnimation(Animation animation):开始动画.

---------------------------------------------------------------------------------------------------------

            ╔════════╗
╠════╣    第Ad个    ╠══════════════════════════════════════════════════╣
            ╚════════╝

●·● Toast 类

1. A toast is a view containing a quick little message for the user. The toast class helps you create and show those.

2. Toast Methods:

  • makeText(Context context, int resId, int duration):返回值:static Toast. Make a standard toast that just contains a text view with the text from a resource.
  • makeText(Context context, CharSequence text, int duration):返回值:static Toast. Make a standard toast that just contains a text view.
  • setDuration(int duration):Set how long to show the view for.
  • setGravity(int gravity, int xOffset, int yOffset):Set the location at which the notification should appear on the screen.
  • getXGravity():返回值:int. Return the X offset in pixels to apply to the gravity's location.
  • getYGravity():返回值:int. Return the Y offset in pixels to apply to the gravity's location.
  • setMargin(float horizontalMargin, float verticalMargin):Set the margins of the view.
  • setText(int resId):Update the text in a Toast that was previously created using one of the makeText() methods.
  • setText(CharSequence s):Update the text in a Toast that was previously created using one of the makeText() methods.
  • show():Show the view for the specified duration.

3. Toast Constants:

  • LENGTH_LONG:Show the view or text notification for a long period of time.
  • LENGTH_SHORTShow the view or text notification for a short period of time.

※ 参考:charSequence--刚认识的接口

举例:

Toast.makeText(getApplicationContext(), "成功", Toast.LENGTH_SHORT).show();    

※ 参考:Android应用开发学习—Toast使用方法大全

---------------------------------------------------------------------------------------------------------

            ╔════════╗
╠════╣    第Ae个    ╠══════════════════════════════════════════════════╣
            ╚════════╝

●·● WebView 类

1. A View that displays web pages.

  Note that, in order for your Activity to access the Internet and load web pages in a WebView, you must add the INTERNET permissions to your Android Manifest file:

<uses-permissionandroid:name="android.permission.INTERNET"/>

2. WebView Methods:

  • canGoBack():
  • canGoForward():
  • canZoomIn():
  • canZoomOut():
  • findNext(boolean forward):
  • getTitle():获取当前网页的标题.
  • getUrl():获取当前网页的 url.
  • getSettings():返回值:WebSettings. 与此相关的设置, 可以设置是否显示放大缩小框.
      WebSettings:管理与 WebView 相关的设置.
        setBuiltInZoomControls(boolean enabled):设置放大缩小控件.
        setDisplayZoomControls(boolean enabled):设置是否显示, 前提上面为 true.
  • goBack():
  • goForward():
  • loadUrl(String url):加载指定 url 的网址.
  • onKeyDown(int keyCode, KeyEvent event):
  • onKeyUp(int keyCode, KeyEvent event):
  • onKeyMultiple(int keyCode, int repeatCount, KeyEvent event):
  • onTouchEvent(MotionEvent event):
  • pageDown(boolean bottom):
  • pageUp(boolean top):
  • reload():重新加载当前网页.
  • stopLoading():停止加载当前网页.
  • zoomIn():
  • zoomOut():
  • setWebViewClient(WebViewClient client):设置接收通知和请求的 WebViewClient.
View Code
public class MyBrowserActivity extends Activity {
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.browser);
        Uri url = getIntent().getData();
        WebView webView = (WebView) findViewById(R.id.WebView01);
        webView.setWebViewClient(new Callback());
        webView.loadUrl(url.toString());
    }
    private class Callback extends WebViewClient {
        @Override
        public boolean shouldOverrideUrlLoading
        (WebView view, String url) {
            return(false);
        }
    }
}

※ 参考:Android webView 使用方法

WebViewActivity.java
 1 public class WebViewActivity extends Activity {
 2     /** Called when the activity is first created. */
 3     @Override
 4     public void onCreate(Bundle savedInstanceState) {
 5         super.onCreate(savedInstanceState);
 6         setContentView(R.layout.main);
 7         
 8         WebView wv = (WebView) findViewById(R.id.webview1);
 9                 
10         WebSettings webSettings = wv.getSettings();
11         webSettings.setBuiltInZoomControls(true);
12         /*
13         wv.loadUrl(
14             "http://chart.apis.google.com/chart" +
15             "?chs=300x225" +
16             "&cht=v" +
17             "&chco=FF6342,ADDE63,63C6DE" +
18             "&chd=t:100,80,60,30,30,30,10" +
19             "&chdl=A|B|C");
20             */
21         
22         /*
23         wv.setWebViewClient(new Callback());
24         wv.loadUrl("http://www.wrox.com");
25         */
26 
27         /*
28         final String mimeType = "text/html";
29         final String encoding = "UTF-8";
30         String html = "<H1>A simple HTML page</H1><body>" +
31             "<p>The quick brown fox jumps over the lazy dog</p></body>";
32         wv.loadDataWithBaseURL("", html, mimeType, encoding, "");
33         */
34         
35         wv.loadUrl("file:///android_asset/Index.html");
36     }
37     
38     private class Callback extends WebViewClient {
39         @Override
40         public boolean shouldOverrideUrlLoading(WebView view, String url) {
41             return(false);
42         }
43     }
44 }

下载源代码:WebView.zip

---------------------------------------------------------------------------------------------------------

            ╔════════╗
╠════╣    第Af个    ╠══════════════════════════════════════════════════╣
            ╚════════╝

●·● ToggleButton 类

1. Displays checked/unchecked states as a button with a "light" indicator and by default accompanied with the text "ON" or "OFF".

2. ToggleButton XML Attributes:

  • android:disabledAlpha:The alpha to apply to the indicator when disabled.
  • android:textOff:The text for the button when it is not checked.
  • android:textOn:The text for the button when it is checked.

3. CheckBox Methods:

  • setOnClickListener(View.OnClickListener l):被点击的时候触发.

---------------------------------------------------------------------------------------------------------

            ╔════════╗
╠════╣    第Ag个    ╠══════════════════════════════════════════════════╣
            ╚════════╝

●·● AutoCompleteTextView 类

1. 可以自动完成的 EditView. 但要提前加入字符串数组.

2. AutoCompleteTextView XML Attributes:

  • android:completionThreshold:几个字母开始出现下拉列表.  → setThreshold(int)
  • android:dropDownHeight:下拉列表高度.  → setDropDownHeight(int)
  • android:dropDownWidth:下拉列表宽度.  → setDropDownWidth(int)
  • android:dropDownHorizontalOffset:="300dp" 下拉列表水平偏移距离.
  • android:dropDownVerticalOffset:="300dp" 下拉别表垂直偏移距离.
  • android:popupBackground:下拉列表背景颜色.  → setDropDownBackgroundResource(int)
  • android:lines:显示行数.  → setLines(int)

3. AutoCompleteTextView Methods:

  • setAdapter(T adapter):
      
        String[] presidents = { ... };  //字符串数组
        ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
                android.R.layout.simple_dropdown_item_1line, presidents);  //数组加入到 ArrayAdapter 中, 默认显示模式.
        AutoCompleteTextView textView = (AutoCompleteTextView) findViewById(R.id.txtCountries);
        textView.setAdapter(adapter);  //将 adapter 与 AutoCompleteTextView 连接.
  • setOnClickListener(View.OnClickListener listener):
  • setOnItemClickListener(AdapterView.OnItemClickListener l):下拉列表被点击的时候触发.
      onItemClick (AdapterView<?> parent, View view, int position, long id):必须实现的方法.
        第一个参数:点击的时候显示的 AdapterView.

        第一个参数:每个点击的控件, 实际上是个 TextView, 可以获取文本.
        后两个参数:在下拉列表中显示的位置.
  • setOnItemSelectedListener(AdapterView.OnItemSelectedListener l):

---------------------------------------------------------------------------------------------------------

            ╔════════╗
╠════╣    第Ah个    ╠══════════════════════════════════════════════════╣
            ╚════════╝

●·● TimePicker 类

1. 时间的显示, 包括24小时的和AM/PM模式的.

2. TimePicker XML Attributes:

  • android:alpha:透明度.   → setAlpha(float)
  • android:background:背景色.  → setBackgroundResource(int)

3. TimePicker Methods:

  • getCurrentHour():获取当前的小时数.
  • getCurrentMinute():获取当前的分钟数.
  • is24HourView():是否为24小时制.
  • setCurrentHour(Integer currentHour):设置当前小时的值.
  • setCurrentMinute(Integer currentMinute):设置当前分钟的值.
  • setIs24HourView(Boolean is24HourView):设置为24小时制.
  • setOnTimeChangedListener(TimePicker.OnTimeChangedListener onTimeChangedListener)
      onTimeChanged (TimePicker view, int hourOfDay, int minute):TimePicker, 小时, 分钟.

---------------------------------------------------------------------------------------------------------

            ╔════════╗
╠════╣    第Ai个     ╠══════════════════════════════════════════════════╣
            ╚════════╝

●·● DatePicker 类

1. 日期的显示.

2. DatePicker Methods:

  • getDayOfMonth()
  • getMonth()
  • getYear()



---------------------------------------------------------------------------------------------------------

            ╔════════╗
╠════╣    第D1个    ╠══════════════════════════════════════════════════╣
            ╚════════╝

●·● FrameLayout 类

1. FrameLayout is designed to block out an area on the screen to display a single item.

  都是叠加在同一个区块,以最大的区块显示为框架。

效果:

实现代码:

    六个按钮实现上图.xml
    <FrameLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_margin="20dip" >
        
        <Button
            android:layout_width="160dip"
            android:layout_height="160dip"
            android:background="#000000" />

        <Button
            android:layout_width="100dip"
            android:layout_height="50dip"
            android:layout_gravity="bottom"
            android:layout_marginLeft="3dip"
            android:layout_marginBottom="3dip"
            android:background="#FF0000" />
        
        <Button
            android:layout_width="100dip"
            android:layout_height="50dip"
            android:layout_gravity="right"
            android:layout_marginRight="3dip"
            android:layout_marginTop="3dip"
            android:background="#00FF00" />
        
        <Button
            android:layout_width="50dip"
            android:layout_height="100dip"
            android:layout_gravity="left"
            android:layout_marginLeft="3dip"
            android:layout_marginTop="3dip"
            android:background="#00FFFF" />
        
        <Button
            android:layout_width="50dip"
            android:layout_height="100dip"
            android:layout_gravity="bottom|right"
            android:layout_marginRight="3dip"
            android:layout_marginBottom="3dip"
            android:background="#FF00FF" />
        
        <Button
            android:layout_width="46dip"
            android:layout_height="46dip"
            android:layout_marginLeft="57dip"
            android:layout_marginTop="57dip"
            android:background="#FFFF00" />
    
    </FrameLayout>

---------------------------------------------------------------------------------------------------------

            ╔══════════╗
╠════╣     第D1¼个    ╠══════════════════════════════════════════════════╣
            ╚══════════╝

●·● ScrollView 类

1. 用来实现垂直滚动的效果,由于此类继承自 FrameLayout 类,因此内部要加入相应的布局控件才好用,否则都堆在一起了,例如在 ScrollView 内部加入一个 LinearLayout 或是 RelativeLayout等等。

java.lang.Object
   ↳    android.view.View
        ↳    android.view.ViewGroup
             ↳    android.widget.FrameLayout
                  ↳    android.widget.ScrollView

---------------------------------------------------------------------------------------------------------

            ╔══════════╗
╠════╣     第D1½个    ╠══════════════════════════════════════════════════╣
            ╚══════════╝

●·● HorizontalScrollView 类

1. 同上面的 ScrollView 相对应,HorizontalScrollView 是专门设计为水平滚动效果的。而且它们之间也可以进行相应的嵌套。

效果:

  

第一幅图是最初效果,第二幅图则是上面两个 HorizontalScrollView 往右移动的效果,第三幅图则是整体 ScrollView 往下移动的效果。

实现代码:

<ScrollView>    //实现最外面一层可以垂直滚动的.
    <LinearLayout>  //垂直滚动内部加入 LinearLayout, 内部加入其它的三个 ScrollView.
        <View/>  //用于分割.
        <HorizontalScrollView>  //第一个水平 ScrollView.
            <LinearLayout>    //内部水平 LinearLayout.
                <Button/>    //水平的 N 个 Button.
            </LinearLayout>
        </HorizontalScrollView>
        <View/>  //用于分割.
        <HorizontalScrollView>  //第二个水平 ScrollView.
            <LinearLayout>    //内部水平 LinearLayout.
                <Button/>
            </LinearLayout>
        </HorizontalScrollView>
        <View/>  //用于分割.
        <ScrollView>      //第三个垂直 ScrollView.
            <LinearLayout>    //内部垂直 LinearLayout
                <Button/>
            </LinearLayout>
        </ScrollView>
    </LinearLayout>
</ScrollView>
    原版.xml
        <Button
            android:id="@+id/Button02"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="center_vertical"
            android:text="Button02" />

        <Button
            android:id="@+id/Button03"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="center_vertical"
            android:text="Button03" />

        <Button
            android:id="@+id/Button04"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="center_vertical"
            android:text="Button04" />

        <Button
            android:id="@+id/button1"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="center_vertical"
            android:text="Button05" />
        
        <Button
            android:id="@+id/Button01"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="center_vertical"
            android:text="Button06" />

        <Button
            android:id="@+id/Button02"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="center_vertical"
            android:text="Button07" />

        <Button
            android:id="@+id/Button03"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="center_vertical"
            android:text="Button08" />

---------------------------------------------------------------------------------------------------------

            ╔════════╗
╠════╣    第D2个    ╠══════════════════════════════════════════════════╣
            ╚════════╝

●·● LinearLayout 类

1. A Layout that arranges its children in a single column or a single row.

java.lang.Object
   ↳    android.view.View
        ↳    android.view.ViewGroup
             ↳    android.widget.LinearLayout

2. LinearLayout XML Attributes:

  • android:orientation:显示的方向, 水平或是垂直的.
  • android:layout_width:宽度.
  • android:layout_height:高度.
  • android:layout_weight:所占权重.

3. LinearLayout Methods:

  • getOrientation()
  • setGravity(int gravity) 
  • setOrientation(int orientation)

---------------------------------------------------------------------------------------------------------

            ╔════════╗
╠════╣    第D3个    ╠══════════════════════════════════════════════════╣
            ╚════════╝

●·● RelativeLayout 类

1. A Layout where the positions of the children can be described in relation to each other or to the parent.

2. RelativeLayout 中控件可以使用的 XML Attributes:

  • android:layout_above:将该控件的底部于给定 ID 的控件之上.【居于之上】
  • android:layout_below:将该控件的顶部于给定 ID 的控件之下.【居于之下】
  • android:layout_toLeftOf:将该控件的右边缘和给定 ID 的控件的左边缘对齐.【居于左边】
  • android:layout_toRightOf:将该控件的左边缘和给定 ID 的控件的右边缘对齐.【居于右边】

  • android:layout_alignBaseline:将该控件的 baseline 和给定 ID 的控件的 baseline 对齐.【居中对齐】
  • android:layout_alignBottom:将该控件的底部边缘和给定 ID 的控件的底部边缘对齐.【底部对齐】
  • android:layout_alignLeft:将该控件的左边缘和给定 ID 的控件的左边缘对齐.【左对齐】
  • android:layout_alignRight将该控件的右边缘和给定 ID 的控件的右边缘对齐.【右对齐】
  • android:layout_alignTop将该控件的顶部边缘和给定 ID 的控件的部边缘对齐.【顶部对齐】

  • android:layout_alignParentBottom:如果该值为 true,则将该控件的底部和父控件的底部对齐.【父控件底对齐】
  • android:layout_alignParentLeft如果该值为 true,则将该控件的左边和父控件的左边对齐.【父控件左对齐】
  • android:layout_alignParentRight如果该值为 true,则将该控件的右边和父控件的右边对齐.【父控件右对齐】
  • android:layout_alignParentTop如果该值为 true,则将该控件的顶部和父控件的顶部对齐.【父控件顶对齐】

  • android:layout_centerHorizontal如果该值为 true,则将该控件将被置于水平方向的中央.【水平居中】
  • android:layout_centerInParent如果该值为 true,则将该控件将被置于水平和垂直方向的中央.【水平垂直居中】
  • android:layout_centerVertical如果该值为 true,则将该控件将被置于垂直方向的中央.【垂直居中】

---------------------------------------------------------------------------------------------------------

            ╔════════╗
╠════╣    第D4个    ╠══════════════════════════════════════════════════╣
            ╚════════╝

●·● GridView 类

1. A view that shows items in two-dimensional scrolling grid.

    main.xml
 1 <?xml version="1.0" encoding="utf-8"?>
 2 <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
 3     android:layout_width="fill_parent"
 4     android:layout_height="fill_parent"
 5     android:orientation="vertical" >
 6 
 7 <GridView 
 8     android:id="@+id/gridview"
 9     android:layout_width="fill_parent" 
10     android:layout_height="fill_parent"
11     android:numColumns="auto_fit"
12     android:verticalSpacing="10dp"
13     android:horizontalSpacing="10dp"
14     android:columnWidth="90dp"
15     android:stretchMode="columnWidth"
16     android:gravity="center" />
17 
18 </LinearLayout>
    GridActivity.java
 1 public class GridActivity extends Activity {
 2     //---the images to display---
 3     Integer[] imageIDs = {
 4             R.drawable.pic1,
 5             R.drawable.pic2,
 6             R.drawable.pic3,
 7             R.drawable.pic4,
 8             R.drawable.pic5,
 9             R.drawable.pic6,
10             R.drawable.pic7
11     };
12 
13     /** Called when the activity is first created. */
14     @Override
15     public void onCreate(Bundle savedInstanceState) {
16         super.onCreate(savedInstanceState);
17         setContentView(R.layout.main);
18         
19         GridView gridView = (GridView) findViewById(R.id.gridview);
20         gridView.setAdapter(new ImageAdapter(this));
21 
22         gridView.setOnItemClickListener(new OnItemClickListener()
23         {
24             public void onItemClick(AdapterView<?> parent,
25             View v, int position, long id)
26             {
27                 Toast.makeText(getBaseContext(),
28                         "pic" + (position + 1) + " selected",
29                         Toast.LENGTH_SHORT).show();
30             }
31         });
32 
33     }
34     
35     public class ImageAdapter extends BaseAdapter 
36     {
37         private Context context;
38 
39         public ImageAdapter(Context c)
40         {
41             context = c;
42         }
43 
44         //---returns the number of images---
45         public int getCount() {
46             return imageIDs.length;
47         }
48 
49         //---returns the item---
50         public Object getItem(int position) {
51             return position;
52         }
53 
54         //---returns the ID of an item---
55         public long getItemId(int position) {
56             return position;
57         }
58 
59         //---returns an ImageView view---
60         public View getView(int position, View convertView,
61         ViewGroup parent)
62         {
63             ImageView imageView;
64             if (convertView == null) {
65                 imageView = new ImageView(context);
66                 imageView.setLayoutParams(new
67                     GridView.LayoutParams(85, 85));
68                 imageView.setScaleType(
69                     ImageView.ScaleType.CENTER_CROP);
70                 imageView.setPadding(5, 5, 5, 5);
71             } else {
72                 imageView = (ImageView) convertView;
73             }
74             imageView.setImageResource(imageIDs[position]);
75             return imageView;
76         }
77     }
78 }

源代码下载:Grid.zip

---------------------------------------------------------------------------------------------------------

            ╔════════╗
╠════╣    第D6个    ╠══════════════════════════════════════════════════╣
            ╚════════╝

●·● TableLayout 类

1. A layout that arranges its children into rows and columns.

2. TableLayout XML Attributes:

  • android:stretchColumns:表格没办法填充满的时候, 需要拉伸的列. (0为第一列索引)
  • android:shrinkColumns:设置允许被收缩的列的序号,多个之间用逗号分隔.
  • android:collapseColumns:设置需要隐藏的列的序号,多个之间用逗号分隔.

3. TableLayout Methods:

  • addView(View child):增加一个子控件. 没有 layoutparams, 就用默认的.
  • addView(View child, int index):放置的位置.
  • addView(View child, int index, ViewGroup.LayoutParams params)
  • addView(View child, ViewGroup.LayoutParams params)

  • isColumnCollapsed(int columnIndex):指定的列是否隐藏.
  • isColumnShrinkable(int columnIndex):指定的列是否收缩.
  • isColumnStretchable(int columnIndex):指定的列是否拉伸.
  • isShrinkAllColumns()
  • isStretchAllColumns()
  • setColumnCollapsed(int columnIndex, boolean isCollapsed):为指定列设置或者解除隐藏.
  • setColumnShrinkable(int columnIndex, boolean isShrinkable)
  • setColumnStretchable(int columnIndex, boolean isStretchable)

  • removeView(View view):删除内部指定的控件.
  • removeViewAt(int index):删除内部指定索引的控件.
  • removeAllViews():删除内部所有控件.

※ 参考:Android-TableLayout布局

※ 参考:Android入门第四篇之TableLayout (一)

※ 参考:Android UI学习 - TableLayout

※ 参考:Android中文API(116)——TableLayout

※ 参考:android TableLayout的使用说明收集

---------------------------------------------------------------------------------------------------------

            ╔════════╗
╠════╣    第D7个    ╠══════════════════════════════════════════════════╣
            ╚════════╝

●·● TableRow 类

1. A layout that arranges its children horizontally. Table 中的每一行, 在行内部可以加入控件, 控件按列排放, 宽度以最宽的为基准.

2. 内部控件具有的 XML Attributes:

  • android:layout_span:合并单元格,等于几,就合并几个单元格.
  • android:layout_column:指定在哪里显示,从0开始算起.
  • android:layout_weight:所占权重,自定义单元格大小比例.

☀☀☀<< 举例 >>☀☀☀

效果:

实现代码:

View Code
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:padding="5dip"        //整体布局留出个边框
    android:background="#aaaaaa"      //设置背景颜色
    android:layout_width="match_parent"
    android:layout_height="match_parent" >

    <TableLayout
        android:id="@+id/tablelayout1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:stretchColumns="1"        //第二列可以自动延伸
        android:layout_alignParentLeft="true"    //居于左上
        android:layout_alignParentTop="true">

        <TableRow
            android:id="@+id/tableRow1"
            android:background="#000000"      //设置黑色背景色
            android:layout_width="wrap_content"
            android:layout_height="wrap_content" >
            
            <TextView                 //第一列
                android:layout_width="80dip"      //第一列的列宽
                android:layout_height="50dip"      
                android:background="#33B5E5"    //背景色
                android:layout_marginLeft="3dip"    //左外边距
                android:layout_marginTop="3dip"    //右外边距
                android:gravity="center"        //文本居中
                android:text="TextView1"        //显示内容
                />
            
            <TextView                 //第二列
                android:layout_width="80dip"
                android:layout_height="50dip"
                android:background="#AA66CC"
                android:layout_marginLeft="3dip"
                android:layout_marginTop="3dip"
                android:gravity="center"
                android:text="TextView1"
                />
            
            <TextView               //第三列
                android:layout_width="80dip"
                android:layout_height="50dip"
                android:background="#99CC00"
                android:layout_marginLeft="3dip"
                android:layout_marginRight="3dip"
                android:layout_marginTop="3dip"
                android:gravity="center"
                android:text="TextView1"
                />
            
        </TableRow>

        <TableRow
            android:id="@+id/tableRow2"
            android:background="#000000"
            android:layout_marginBottom="3dip"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content" >
            
            <TextView 
                android:layout_height="50dip"
                android:background="#FFBB33"
                android:layout_marginLeft="3dip"
                android:layout_marginTop="3dip"
                android:gravity="center"
                android:text="TextView2"
                />
            
            <TextView 
                android:layout_width="80dip"
                android:layout_height="50dip"
                android:background="#00FF00"
                android:layout_marginLeft="3dip"
                android:layout_marginTop="3dip"
                android:gravity="center"
                android:text="TextView3"
                />
            
            <TextView 
                android:layout_width="80dip"
                android:layout_height="50dip"
                android:background="#FFBB33"
                android:layout_margin="3dip"
                android:gravity="center"
                android:text="TextView1"
                />

        </TableRow>

        
        <View                //中间的分隔符
            android:layout_height="5dip"    //高度为5dip
            android:background="#000"    //背景颜色
            />
        
        <TableRow
            android:id="@+id/tableRow3"
            android:background="#000000"
            android:layout_marginTop="3dip"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content" >
            
            <TextView 
                android:layout_width="80dip"
                android:layout_height="50dip"
                android:background="#FF4444"
                android:layout_marginLeft="3dip"
                android:layout_marginTop="3dip"
                android:layout_marginRight="3dip"
                android:layout_span="3"
                android:gravity="center"
                android:text="合并(android:layout_span)"
                />
            
        </TableRow>

        <TableRow
            android:id="@+id/tableRow4"
            android:background="#000000"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content" >
            
            <TextView 
                android:layout_height="50dip"
                android:background="#00FF00"
                android:layout_marginLeft="3dip"
                android:layout_marginTop="3dip"
                android:layout_marginBottom="3dip"
                android:gravity="center"
                android:text="TextView7"
                />
            
            <TextView 
                android:layout_height="50dip"
                android:background="#FFF"
                android:layout_marginLeft="3dip"
                android:layout_marginTop="3dip"
                android:layout_marginBottom="3dip"
                android:gravity="center"
                android:text="TextView8"
                />
            
            <TextView 
                android:layout_height="50dip"
                android:background="#00FF00"
                android:layout_margin="3dip"
                android:gravity="center"
                android:text="TextView9"
                />
            
        </TableRow>
        
    </TableLayout>
        
       <TableLayout
           android:layout_width="match_parent"
           android:layout_height="wrap_content" 
           android:layout_marginTop="10dip"
           android:layout_below="@id/tablelayout1" >  //第二个 tablelayout 位于上面 tablelayout 的下面
    
            <TableRow
            android:id="@+id/tableRow4"
            android:background="#000000"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content" >
            
            <TextView 
                android:layout_weight="1"      //设置先比例权重, 保证均分
                android:layout_height="50dip"
                android:background="#FFFF00"
                android:layout_marginLeft="3dip"
                android:layout_marginTop="3dip"
                android:layout_marginBottom="3dip"
                android:gravity="center"
                android:text="TextView7"
                />
            
            <TextView 
                android:layout_weight="1"      //比例权重
                android:layout_height="50dip"
                android:background="#00FF00"
                android:layout_marginLeft="3dip"
                android:layout_marginTop="3dip"
                android:layout_marginBottom="3dip"
                android:gravity="center"
                android:text="TextView8"
                />
            
            <TextView 
                android:layout_weight="1"      //比例权重
                android:layout_height="50dip"
                android:background="#00FFFF"
                android:layout_margin="3dip"
                android:gravity="center"
                android:text="TextView9"
                />
            
        </TableRow>
    </TableLayout>

</RelativeLayout>

 

http://developer.android.com/reference/android/view/ViewGroup.LayoutParams.html

posted on 2012-07-25 12:55  McDelfino  阅读(1237)  评论(0编辑  收藏  举报