前面一篇使用到了自定义控件视图,通过include方法引用控件,实现了基本的自定义控件,但是对于自定义控件的事件功能实现是建立在单个活动中的,假设有多个子活动需要使用自定义控件,就意味着要分别在多个子活动中重复实现自定义的控件功能,显然这是不被推荐的,这里通过继承实现自定义控件类来解决上面的问题
大部分控件都是单独以layout存在,这里以LinearLayout为例:
视图部分:
<?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="match_parent"
android:orientation="vertical" >
<com.example.menu.TitleLayout android:layout_width="fill_parent" android:layout_height="wrap_content"></com.example.menu.TitleLayout>
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:textSize="16sp"
android:textStyle="normal"
android:layout_marginTop="15dp"
android:layout_marginLeft="15dp"
android:layout_marginRight="15dp"
android:lineSpacingExtra="10dp"
android:text="中国日报网12月11日电(远达)由中国倡导设立的亚洲基础设施投资银行蓄势待发,不少国家摩拳擦掌、踊跃参与,但也有彷徨徘徊者,有的甚至心生疑忌,视之为对亚太金融格局的挑战,认为亚投行要与世行、亚行分庭抗礼。"
/>
</LinearLayout>
package com.example.menu;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;
import android.view.View.OnClickListener;
public class TitleLayout extends LinearLayout implements OnClickListener{
private Button tittle_back,tittle_index;
private Context context;
public TitleLayout(Context context,AttributeSet attrs) {
super(context,attrs);
this.context=context;
LayoutInflater.from(context).inflate(R.layout.title, this);
initView();
}
private void initView(){
tittle_back= (Button) findViewById(R.id.title_back);
tittle_index=(Button) findViewById(R.id.title_index);
tittle_back.setOnClickListener(this);
tittle_index.setOnClickListener(this);
}
public void onClick(View v) {
Activity ac=((Activity) context);
switch (v.getId()) {
case R.id.title_back:
ac.finish();
break;
case R.id.title_index:
Intent intent =new Intent(ac,MainActivity.class);
ac.startActivity(intent);
break;
}
}
}