我们在学习JAVA编程的时候总强调接口编程,怎么使用接口,使用的好处体现在哪里?
以下是我在写Android的一个自定义TitleBar的时候的一个小例子,我们就以这个小例子简单讲述(个人理解)
TitleBarView是继承LinearLayout的控件,它包含1个ImageView 按钮,2个TextView,我们可以在其他布局中直接引用TitleBar 。
我在TitleBar中写了一个点击事件处理接口,负责处理左右两个Button按钮的点击事件(点击事件发生时调用对应的处理方法,而处理方法由调用者实现),同时提供一个绑定监听器的方法
这样我们在其他Activity中引用这个TitleBar 时只需要实现BtnClickListener接口,然后绑定就可以自定义TitleBar按钮的具体效果
而在具体实现过程中,其他地方不需要关注TitleBar的内部原理,只要实现BtnClickListener里的两个方法就可以。
这些就属于接口编程是具体使用。
例子代码:
/**
* 自定义的TitleBar控件
*
* @author baron 提供监听器接口,调用者可以实现监听器接口包含左右两个按钮的点击事件方法 然后绑定监听器
*/
public class TitleBarView extends LinearLayout {
ImageView btnRight;
TextView btnLeft;
TextView tvTitle;
BtnClickListener listener;
public TitleBarView(Context context, AttributeSet attrs) {
super(context, attrs);
init(context);
}
/**
* 初始化组件
*
* @param context
*/
private void init(Context context) {
LayoutInflater.from(context).inflate(R.layout.titlebar, this);
btnLeft = (TextView) findViewById(R.id.btn_left);
btnRight = (ImageView) findViewById(R.id.btn_right);
tvTitle = (TextView) findViewById(R.id.title);
btnLeft.setOnClickListener(new OnClickListener(){
@Override
public void onClick(View v) {
listener.leftClick();
}});
btnRight.setOnClickListener(new OnClickListener(){
@Override
public void onClick(View v) {
listener.rightClick();
}});
}
// 提供绑定自定义监听器方法
public void setTitleBarListener(BtnClickListener listener) {
this.listener = listener;
}
/**
* 按钮点击处理接口,调用者实现
*/
public interface BtnClickListener {
void leftClick();
void rightClick();
}
}
XML代码:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:minHeight="50dp"
android:background="@color/bg_title_bar"
android:orientation="horizontal" >
<TextView
android:id="@+id/btn_left"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:gravity="center"
android:drawableLeft="@drawable/app_back"
android:drawablePadding="4dp"
android:text="@string/txt_left"/>
<TextView
android:id="@+id/title"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="1"
android:text="@string/txt_title"
android:gravity="center" />
<ImageView
android:visibility="invisible"
android:id="@+id/btn_right"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:adjustViewBounds="true"
android:src="@drawable/app_select" />
</LinearLayout>
在自定义TitleBar的时候往往在左右各放置一个Button按钮,但Button在添加图片作为背景(bacakground)的时候,图片容易拉伸。
ImageView中XML属性src和background的区别:
background会根据ImageView组件给定的长宽进行拉伸,而src就存放的是原图的大小,不会进行拉伸。
src是图片内容(前景),bg是背景,可以同时使用。
此外:scaleType只对src起作用;bg可设置透明度,比如在ImageButton中就可以用Android:scaleType控制图片的缩放方式
关于图片拉伸大家可以参考这篇文章解决
http://blog.csdn.net/oathevil/article/details/23707359