Xio习的第四天
前几天一直再弄一些材料,现在继续学这个
引入布局
创建一个标题栏:
- 新建布局title.xml :
具体内容:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<Button
android:id="@+id/title_back"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_margin="5dp"
android:text="back"
android:textColor="#fff"
android:background="@drawable/two"/>
<TextView
android:id="@+id/title_text"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:gravity="center"
android:layout_gravity="center"
android:text="Tltle"
android:textColor="#141313"
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="5dp"
android:background="@drawable/two"
android:text="Edit"
android:textColor="#fff" />
</LinearLayout>
在activity_main.xml;
<include layout="@layout/title"/>
在MainActivity的onCreat中添加:
ActionBar actionBar=getSupportActionBar();
if(actionBar!=null){
actionBar.hide();
}
getSupportActionBar()获得ActionBar的实例,然后调用hide()隐藏原有的标题栏
运行结果如图:
- 自定义控件 :
新建TitleLayout继承LinearLayout:
public class TitleLayout extends LinearLayout {
public TitleLayout(Context context , AttributeSet attrs){
super(context,attrs);
LayoutInflater.from(context).inflate(R.layout.title,this);
}
}
重写了LinearLayout的构造函数,使用TitleLayout控件就会调用这个函数。LayoutInflater可以对标题栏布局进行动态加载,from可以构建一个对象。
然后在activity_main中:
<com.example.selfcontrol.TitleLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
运行程序,结果和之前引入布局相同。这个应该是将布局和控件相关联,通过控件加载布局。
为布局中的两个按钮增加点击实事件:
Button titleBack=(Button)findViewById(R.id.title_back);
Button titleEdit=(Button)findViewById(R.id.title_edit);
titleBack.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
((Activity)getContext()).finish();
}
});
titleEdit.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
Toast.makeText(getContext(),"back",Toast.LENGTH_SHORT).show();
}
});
这样点击回复按键就会销毁当前活动,按Edit按键就会弹出提示框。