今天做项目需要用到一个actionbar,添加一个返回按钮,外加title要能变换;
做了一下操作:
1.创建一个actionbar的布局文件actionbarlayout。在布局文件中放了一个ImageButton和一个TextView
代码如下:
<?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="horizontal"> <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content"> <ImageButton android:id="@+id/actionbarimageButton" android:layout_width="wrap_content" android:layout_height="wrap_content" android:src="@drawable/back_icon" /> <TextView android:id="@+id/actionbartext" android:layout_width="match_parent" android:layout_height="match_parent" android:gravity="center_vertical" android:layout_marginLeft="20dp" android:text="操作平台" android:textColor="#ffffff" android:textSize="20dp" /> </LinearLayout> </LinearLayout>
2.在Acitvity中,先将布局文件转化成View,然后再对View中的组件操作。主要代码如下:
View customView = LayoutInflater.from(this).inflate(R.layout.actionbarlayout, new LinearLayout(this), false); ActionBar actionbar = this.getSupportActionBar(); actionbar.setDisplayShowCustomEnabled(true); actionbar.setCustomView(customView); TextView tv = (TextView) customView.findViewById(R.id.actionbartext); ImageButton im = (ImageButton) customView.findViewById(R.id.actionbarimageButton); im.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { onBackPressed(); } });tv.setText("我是标题");
在ImageButton的点击事件中调用了系统的返回键,在textview中可以变换文字内容,达到变化activity title的效果。
注意:在导入包的时候要导入V7下的包,并让Activity 继承 ActionBarActivity。
import android.support.v7.app.ActionBar; import android.support.v7.app.ActionBarActivity;