myzuhe.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="50dp"
android:background="#ffcb05" >
<Button
android:id="@+id/button_left"
android:layout_width="60dp"
android:layout_height="40dp"
android:layout_centerVertical="true"
android:layout_marginLeft="5dp"
android:background="#ffff05"
android:text="Back"
android:textColor="#fff" />
<TextView
android:id="@+id/title_text"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:text="This is Title"
android:textColor="#fff"
android:textSize="20sp" />
</RelativeLayout>
package com.example.framelayoutuse;
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.FrameLayout;
public class MyTitleView extends FrameLayout{
private Button bt1;
public MyTitleView(Context context, AttributeSet attrs) {
/* AttributeSet attrs
* 写在xml里的 调用2个参数的 attr里边传过来的是 xml里边对应的height width等参数,包括自己定义的参数,
* 如果在xml里边写入自定义控件的话 必须要重写2个参数的构造函数*/
super(context, attrs);
// TODO Auto-generated constructor stub
//实例化对应的组件对象
LayoutInflater.from(context).inflate(R.layout.myzuhe, this);
bt1 = (Button) findViewById(R.id.button_left);
bt1.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
//点击按钮时关闭当前界面,回退到上一级界面
((Activity)getContext()).finish();
}
});
}
}
activity_main.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context=".MainActivity" >
<com.example.framelayoutuse.MyTitleView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/my_list_view" />
</RelativeLayout>
package com.example.framelayoutuse;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}