控件的使用方法一般有两种,一种是xml配置,一种是直接在java程序上调用。游戏开发很少使用xml配置。
java代码:
public void onCreate(Bundle savedInstanceState) {//回调方法
super.onCreate(savedInstanceState);
setContentView(R.layout.main);//设置显示的View
textView = (TextView) this.findViewById(R.id.textView);
button = (Button) this.findViewById(R.id.button);
button.setOnClickListener(this);//为button添加监听器
imageButton = (ImageButton) this.findViewById(R.id.imageButton);
imageButton.setOnClickListener(this);//为imageButton添加监听器
toggleButton = (ToggleButton) this.findViewById(R.id.toggleButton);
toggleButton.setOnClickListener(this);//为toggleButton添加监听器
}
public void onClick(View v) {//重写的事件处理回调方法
if(v == button){//点击的是普通按钮
textView.setText("您点击的是普通按钮");
}
else if(v == imageButton){//点击的是图片按钮
textView.setText("您点击的是图片按钮");
}
else if(v == toggleButton){//点击的是开关按钮
textView.setText("您点击的是开关按钮");
}
}
}
xml代码:
<?xml version="1.0" encoding="utf-8" ?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<TextView android:id="@+id/textView"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="您没有点击任何按钮" />
<Button android:id="@+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="普通按钮" />
<ImageButton android:id="@+id/imageButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@drawable/img" />
<ToggleButton android:id="@+id/toggleButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</LinearLayout>
输出效果:
编写过程遇到的问题主要是 每个文件,图片名都要小写。