目录
单选钮(RadioButton)和复选框(CheckBox)
状态开关按钮(ToggleButton)和开关(Switch)
按钮随着按下动作改变背景:
先编写一个selector.xml:
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<!-- 指定按下时的图片-->
<item android:state_pressed="true"
android:drawable="@drawable/r1"/>
<!-- 指定按钮松开时的图片-->
<item android:state_pressed="false"
android:drawable="@drawable/r2"/>
</selector>
然后设置Button的背景为selector.xml即可。
单选钮(RadioButton)和复选框(CheckBox)
RadioButton通常要和RadioGroup一起使用
<RadioGroup
android:id="@+id/rg"
android:orientation="horizontal"
android:layout_gravity="center_horizontal"
>
<RadioButton
android:id="@+id/male"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:checked="true"
android:text="男"/>
<RadioButton
android:id="@+id/female"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:checked="false"
android:text="女"/>
</RadioGroup>
状态开关按钮(ToggleButton)和开关(Switch)
<ToggleButton
android:id="@+id/toggle"
android:textOff="关"
android:textOn="开"
android:checked="true"
android:background="@drawable/r1"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<Switch
android:id="@+id/switchTest"
android:textOn="开心"
android:textOff="开"
android:checked="true"
android:text="测试"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
多个按钮点击事件实现的新思路
//先把listener创建出来,在监听器里面对不同的View对象,也就是不同的组件的id做判断
View.OnClickListener listener = new View.OnClickListener() {
@Override
public void onClick(View v) {
switch (v.getId()){
case R.id.plus:
if (alpha < 255)
alpha += 20;break;
case R.id.minus:
if (alpha >20)
alpha -= 20;break;
}
image1.setImageAlpha(alpha);
}
};
//最后在把监听器和按钮绑定在一起
plus.setOnClickListener(listener);
minus.setOnClickListener(listener);
ZoomControls的使用:
zoomControls.setOnZoomInClickListener
zoomControls.setOnZoomOutClickListener
ImageView的使用:
image1.setOnTouchListener(new View.OnTouchListener() {
@RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN)
@Override
public boolean onTouch(View v, MotionEvent event) {
a = event.getX();
b = event.getY();
change(a,b,zoom);
return false;
}
});
event是触摸事件,,通过getX(),getY(),获得触摸时的坐标。
public void change(float xx, float yy,int zoom){
//获取第一个图片显示框的位图
//BitmapDrawable bitmapDrawable = (BitmapDrawable) image1.getDrawable();
//bitmap = bitmapDrawable.getBitmap();
//bitmap图片实际大小与第一个ImageView的缩放比例
double scale = 1.0 * bitmap.getHeight() / image1.getHeight();
//获取需要显示的图片的开始点
//round 是四舍五入
x = Math.round(xx * scale);
y = Math.round(yy * scale);
if (x + zoom > bitmap.getWidth()){
x = bitmap.getWidth()- zoom;
}
if(y + zoom > bitmap.getHeight()){
y = bitmap.getHeight() - zoom;
}
image2.setImageBitmap(Bitmap.createBitmap(bitmap,(int)x,(int)y,zoom,zoom));
image2.setImageAlpha(alpha);
}
Bitmap createBitmap( Bitmap source, int x, int y, int width, int height)
source为源图,x、y为起始坐标,width,height为宽和高。此函数为ROI,截取感兴趣的区域。