Android ApiDemo 系列解析【View->Button】
- 1、本篇讲述点在 ApiDemos 位置。
- 2、为Button 添加系统样式。
- 3、额外扩展。
- src文件
com.example.android.apis.view 下的 Buttons1.java文件 源码为:
ApiDemos src 代码
package com.example.android.apis.view;
import com.example.android.apis.R;
import android.app.Activity;
import android.os.Bundle;
public class Buttons1 extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super .onCreate(savedInstanceState);
setContentView(R.layout.buttons_1);
}
}
- res 文件
layout 下的 buttons_1.xml 文件, 源码为:
< ScrollView xmlns:android ="http://schemas.android.com/apk/res/android"
android:layout_width ="fill_parent"
android:layout_height ="fill_parent" >
< LinearLayout
android:layout_width ="wrap_content"
android:layout_height ="wrap_content"
android:orientation ="vertical" >
<!-- Regular sized buttons -->
< Button android:id ="@+id/button_normal"
android:text ="@string/buttons_1_normal"
android:layout_width ="wrap_content"
android:layout_height ="wrap_content" />
<!-- Small buttons -->
< Button android:id ="@+id/button_small"
style ="?android:attr/buttonStyleSmall"
android:text ="@string/buttons_1_small"
android:layout_width ="wrap_content"
android:layout_height ="wrap_content" />
< ToggleButton android:id ="@+id/button_toggle"
android:text ="@string/buttons_1_toggle"
android:layout_width ="wrap_content"
android:layout_height ="wrap_content" />
</ LinearLayout >
</ ScrollView >
- 1、如何在 布局中找到 View 即你要的按钮
- 2、为 Button 添加事件监听
- 3、为 Button 添加按上按下切换图片效果
- 4、为 ToggleButton 添加状态改变事件监听
normal = (Button) findViewById(R.id.button_normal);
small = (Button) findViewById(R.id.button_small);
btn = (ToggleButton) findViewById(R.id.button_toggle);
}
代码如下:
btn.setOnClickListener( new OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
switch (v.getId()) {
case R.id.button_normal:
setTitle( " 点击了普通按钮 " );
break ;
case R.id.button_small:
setTitle( " 点击小按钮 " );
break ;
default :
break ;
}
}
});
}
代码如下:
btn.setOnTouchListener( new OnTouchListener() {
public boolean onTouch(View v, MotionEvent event) {
// TODO Auto-generated method stub
switch (event.getAction()) {
case MotionEvent.ACTION_UP:
btn.setBackgroundResource(R.drawable.add);
break ;
case MotionEvent.ACTION_DOWN:
btn.setBackgroundResource(R.drawable.add_user);
break ;
default :
break ;
}
return false ;
}
});
}
代码如下:
public void onCheckedChanged(CompoundButton buttonView,
boolean isChecked) {
// TODO Auto-generated method stub
if (isChecked) {
setTitle( " 选中 " );
} else {
setTitle( " 反选 " );
}
}
});