找到在XML布局文件中定义的VIEW控件

为了找到一个在XML布局文件中被定义的View控件,首先要做的是在控件定义中添加android:id属性。如下:

1
2
3
4
5
6
7
<?xml version="1.0" encoding="utf-8"?>	
<Button xmlns:android="http://schemas.android.com/apk/res/android"
    android:id ="@+id/btn_search"
    android:gravity="center"
    android:layout_width ="300px"
    android:layout_height = "wrap_content"
    android:text ="Search" />

编译时会自动在R.java文件中添加该按钮的android:id定义,如:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
package org.gooss.android.linearlayout;
 
public final class R {
    //.....
    public static final class id {
        public static final int btn_search=0x7f050000;
    }
    public static final class layout {
        public static final int main=0x7f030000;
    }
    public static final class string {
        public static final int app_name=0x7f040000;
        public static final int red=0x7f040001;
    }
   // ......
}

在一个Activity中找到该按钮也非常简单:

1
2
/* Find the Button from our XML-layout. */
Button b = (Button) this.findViewById(R.id.btn_search );

如果Eclipse不能找到Button类,只要敲击”Ctrl+Shift+O”即可自动导入:

1
import android.widget.Button;

Monitor Your Web Site 24/7 - Receive email and SMS alerts anytime your web site goes down.

Related Posts

Leave a Reply

Monitor Your Web Site 24/7 - Receive email and SMS alerts anytime your web site goes down.

About Me

About Me
Record Technical Articles at Gooss.org.

Entries (RSS) and Comments (RSS). Valid XHTML and CSS and XFN.

© Copyright 2009 山海经. All rights reserved.

Social Bookmarks

Copyright © Designed by: Free WP Templates
Food Charts |  About Breast Milk |  Organic Food