自定义组件:
1.创建自定义组件
2.引入组件
//1.新建TitleLayout.java
public class TitleLayout extends LinearLayout {
public TitleLayout(Context context, AttributeSet attrs) {
super(context,attrs);
LayoutInflater.from(context).inflate(R.layout.title,this);
Button titleBack = (Button)findViewById(R.id.title_back);
titleBack.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
((Activity)getContext()).finish();
}
});
Button titleEdit = (Button) findViewById(R.id.title_Edit);
titleEdit.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
Toast.makeText(getContext(),"分享到朋友圈",Toast.LENGTH_SHORT).show();
}
});
}
}
// 2. 布局文件
<?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:orientation="horizontal"
android:background="#ff333333">
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/title_back"
android:text="返回"
android:gravity="center"
android:background="#ff333333"
android:textColor="#ffffffff"
/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="新闻中心"
android:gravity="center"
android:layout_weight="1"
android:id="@+id/title"
android:textColor="#ffffffff"/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/title_Edit"
android:gravity="center"
android:text="分享"
android:background="#ff333333"
android:textColor="#ffffffff"
/>
</LinearLayout>
// 3.在需要处引入
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
xmlns:android="http://schemas.android.com/apk/res/android">
//引入------
<com.example.myapplication1.TitleLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
//-------引入
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="产品"/>
</LinearLayout>