出现问题
在布局文件中使用
Activity中的代码
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
TextView textView = (TextView) findViewById(R.id.text_include);
RelativeLayout rl_include = (RelativeLayout) findViewById(R.id.rl_layout);
rl_include.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Toast.makeText(MainActivity.this, "text", Toast.LENGTH_SHORT).show();
}
});
}
activity_main.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/activity_main"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context="com.example.administrator.mytestapp.MainActivity">
<include
android:id="@+id/include"
layout="@layout/layout_inclue" />
<TextView
android:id="@+id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_marginTop="135dp"
android:text="Hello World!" />
</RelativeLayout>
layout_inclue.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/rl_layout"
android:layout_width="match_parent"
android:layout_height="45dp"
android:background="@android:color/darker_gray"
android:orientation="vertical">
<TextView
android:id="@+id/text_include"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:text="INCLUDE_TITLE"
android:textColor="@android:color/holo_red_dark" />
</RelativeLayout>
出错的地方
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.RelativeLayout.setOnClickListener(android.view.View$OnClickListener)' on a null object reference
是在设置layout_inclue布局中相对布局点击事件出现空指针的问题,最后是发现是activity_main.xml中
提供两个解决方法
1.删除activity_main.xml中标签的id,程序即可正常运行
2.使用activity_main.xml中标签的id
RelativeLayout rl_include = (RelativeLayout) findViewById(R.id.include);
rl_include.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Toast.makeText(MainActivity.this, "text", Toast.LENGTH_SHORT).show();
}
});