最近开始跟着郭霖大神的《第一行代码》学习Android开发,遇到一个问题
自定义布局之后,模拟器运行时Button不响应单击事件
代码如下
MainActivity.java
package com.example.uilayouttest;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ActionBar actionBar = getSupportActionBar();
if (actionBar != null){
actionBar.hide();
}
}
}
activity_main.xml文件
<?xml version="1.0" encoding="UTF-8"?>
android:layout_width="match_parent"
android:layout_height="match_parent">
<!--android:orientation="horizontal"-->
<include layout="@layout/title"/>
<com.example.uilayouttest.TitleLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
</com.example.uilayouttest.TitleLayout>
title.xml文件
<?xml version="1.0" encoding="utf-8"?>
android:layout_width="match_parent"
android:layout_height="65dp"
android:background="@drawable/back_bg"
>
<Button
android:id="@+id/title_back"
android:layout_width="60dp"
android:layout_height="60dp"
android:layout_gravity="top"
android:layout_margin="5dp"
android:text="Back"
android:textColor="#fff"/>
<TextView
android:id="@+id/title_text"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_gravity="top"
android:layout_weight="1"
android:gravity="center"
android:text="Title Text"
android:textColor="#fff"
android:textSize="28sp"/>
<Button
android:id="@+id/title_edit"
android:layout_width="60dp"
android:layout_height="60dp"
android:layout_gravity="top"
android:layout_margin="5dp"
android:background="@drawable/edit"
android:text=""
/>
TitleLayout.java类
package com.example.uilayouttest;
import android.app.Activity;
import android.content.Context;
import android.util.AttributeSet;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.Toast;
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);
Button titleEdit = (Button) findViewById(R.id.title_edit);
titleBack.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
((Activity) getContext()).finish();
Log.d("data", "onClick:到底有没有点击我 ");
Toast.makeText(getContext(), "你点击了Back按钮", Toast.LENGTH_SHORT).show();
}
});
titleEdit.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
Toast.makeText(getContext(), "你点击了Edit按钮", Toast.LENGTH_SHORT).show();
}
});
}
}