构建一个简单的用户界面
在res/layout/activity_main.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity" >
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/hello_world" />
</RelativeLayout>
在这里因为RelativeLayout相对布局是整个视图的根布局,所以对于宽和高都应该是充满整个屏幕的,指定为fill_parent。然而,从Android2.2开始,为了更好的使用,fill_parent被改为match_parent。因为当我们把一个子部件设置为fill_parent之后,该部件不是占有同等级部件剩余的空间,而是和同等级部件重叠在一起。相反,使用match_parent则不会出现重叠的现象。
上面已经添加了一个TextView控件,假如要再添加一个控件需要给控件加上id,并且根据id来摆放控件的位置。如:|
<TextView
android:id="@+id/show"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/hello_world" />
<Button
android:id="@+id/request"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/show"
android:text="@string/hello_world" />
在Button中添加了android:layout_below="@+id/show",对于@string/hello_world需要在values/strings.xml中定义。
格式如下:
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="app_name">HelloWorld</string>
<string name="action_settings">Settings</string>
<string name="hello_world">Hello world!</string>
</resources>
启动一个Activity
通过一个事件来启动,使用Button,如下(当然,还有其他方式):
<Button
android:id="@+id/request"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/show"
android:onClick="methodName"
android:text="@string/hello_world" />
android:onclick属性的值:methodName就是当用户点击你屏幕按钮时触发方法的名字,
/**
* 响应按钮的点击事件
*
* @param v
*/
public void methodName(View v) {
// Do something
Intent intent = new Intent(MainActivity.this,SecondActivity.class);
startActivity(intent);
}
为了让系统能够将这个方法(你刚在MyFirstActivity中添加的sendMessage方法)与在android:onClick属性中提供的方法名字匹配,它们的名字必须一致,特别是,这个方法必须满足以下三个必须:
必须公共的
必须没有返回值
必须有一个唯一的视图(View)参数(这个视图就是将被点击的视图)
在你的项目中,在src/<package-name>/路径下新建一个名为SecondActivity.java的类,
public class SecondActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_second);
}
}
在清当文件中添加<activity android:name="com.example.helloworld.SecondActivity" />