前面一篇使用到了自定義控件視圖,通過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;
}
}
}