android actionbar自定义View并添加点击事件

来源:互联网 发布:seo内部优化包括 编辑:程序博客网 时间:2024/06/05 08:14

LoginActivity.java

public class LoginActivity extends AppCompatActivity {    public static final String TAG = "ZCN_LoginActivity";    private ImageView iv;    @Override    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.activity_login);        ActionBar actionBar = getSupportActionBar();        if (actionBar != null) {            Log.d(TAG,"actionBar不为空");            View titleView = LayoutInflater.from(this).inflate(R.layout.vrepair_actionbar, new LinearLayout(this), false);            actionBar.setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM); //Enable自定义的View            actionBar.setCustomView(titleView);//设置自定义的布局            iv = (ImageView)titleView.findViewById(R.id.iv_actionbar_back);            iv.setOnClickListener(new View.OnClickListener() {                @Override                public void onClick(View view) {                    Log.d(TAG,"=====请输出=====");                }            });        }    }}

vrepair_actionbar.xml文件

<?xml version="1.0" encoding="utf-8"?><RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"    android:orientation="horizontal"    android:layout_width="match_parent"    android:layout_height="match_parent">    <ImageView        android:id="@+id/iv_actionbar_back"        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:layout_centerVertical="true"        android:background="@mipmap/ic_launcher"/>    <TextView        android:id="@+id/tv_actionbar_title"        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:gravity="center"        android:text="aaaaa"        android:layout_centerInParent="true" /></RelativeLayout>

activity_login.xml没什么特别的

<?xml version="1.0" encoding="utf-8"?><LinearLayout 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:background="@color/white"    tools:context="com.sdlj.vehiclerepair.activity.LoginActivity">    <TextView        android:layout_width="match_parent"        android:layout_height="match_parent"        android:text="我是主界面,哈哈哈哈"        android:textColor="@color/black"/></LinearLayout>