패치 워크 사용자 지정 컨트롤
참고 레이아웃 기술은 레이아웃 코드를 재 작성의 문제를 해결 않지만, 최적화의 여지가있다.
예를 들어, 버튼의 기능을 파괴 동일한 제목 표시 줄입니다 이벤트, 뒤로 버튼, 사실, 상관없이 현재 활동.
이 상황은 사용자 지정 컨트롤을 사용하여 해결하는 가장 좋은 방법입니다.
있는 LinearLayout로부터 상속 한 새로운 TitleLayout,이 제목 표시 줄 우리의 사용자 정의를 제어하자
코드는 다음과 같습니다 :
import android.app.Activity;
import android.content.Context;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.Toast;
public class extends LinearLayout {
public (Context context, AttributeSet attrs) {
super(context, attrs);
LayoutInflater.from(context).inflate(R.layout.title, this);
Button titleBack = (Button) findViewById(R.id.title_back);
Button titleEdit = (Button) findViewById(R.id.title_edit);
titleBack.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
((Activity) getContext()).finish();
}
});
titleEdit.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
// 吐司
Toast.makeText(getContext(), "你点击了右侧按钮", Toast.LENGTH_SHORT).show();
}
});
}
}
tiele 레이아웃 파일
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="@drawable/bg_banner" >
<Button
android:id="@+id/title_back"
an 大专栏 拼凑自定义控件droid:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_margin="5dip"
android:background="@drawable/bt_menu_show"
android:text="Back"
android:textColor="#fff" />
<TextView
android:id="@+id/title_text"
android:layout_width="0dip"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_weight="1"
android:gravity="center"
android:text="Title Text"
android:textColor="#fff"
android:textSize="24sp" />
<Button
android:id="@+id/title_edit"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_margin="5dip"
android:background="@drawable/ico_letter"
android:text="Edit"
android:textColor="#fff" />
</LinearLayout>
2 활동의 레이아웃에 사용자 지정 컨트롤 추가
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<com.yassblog.TitleLayout
android:layout_width="match_parent"
android:layout_height="wrap_content" >
</com.yassblog.TitleLayout>
</LinearLayout>