Android 从自定义视图声明布局时的NPE
我有一个类,它扩展了Android 从自定义视图声明布局时的NPE,android,android-layout,android-custom-view,Android,Android Layout,Android Custom View,我有一个类,它扩展了视图,在该类中的某个特定点上,我希望在文本旁边显示一个小图标 为了实现这一点,我创建了如下所示的XML布局,在扩展视图的类中,我定义了布局,使其内容显示在屏幕上,但应用程序因NullPointerException而崩溃 请让我知道如何解决它 更新\u 1: void onsizechanged() { Layoutinflater mlayoutinf = LayoutInflater.from(this.
视图
,在该类中的某个特定点上,我希望在文本旁边显示一个小图标
为了实现这一点,我创建了如下所示的XML布局,在扩展视图的类中,我定义了布局,使其内容显示在屏幕上,但应用程序因NullPointerException而崩溃
请让我知道如何解决它
更新\u 1:
void onsizechanged() {
Layoutinflater mlayoutinf = LayoutInflater.from(this.mcontext;
View mview = mLayoutInf.inflate(R.id.confMSG_Yes,null);
this.tv = (textview) mView.findViewById(R.id.confMSG_Yes)
}
ontouchevent(){
....
....
showconfirmation()
}
showconfirmation() {
this.tv.settext("some text");
}
我已经在onsizeChanged()
中初始化了LayoutInflater
,如下所示,但是当我运行应用程序时,没有显示任何内容
在onSizechanged中初始化:
void onsizechanged() {
Layoutinflater mlayoutinf = LayoutInflater.from(this.mcontext;
View mview = mLayoutInf.inflate(R.id.confMSG_Yes,null);
this.tv = (textview) mView.findViewById(R.id.confMSG_Yes)
}
ontouchevent(){
....
....
showconfirmation()
}
showconfirmation() {
this.tv.settext("some text");
}
xml文件
<?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="vertical" >
<RelativeLayout
android:id="@+id/rL01_ConfMSG"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<TextView
android:id="@+id/confMSG_Header"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:text="@string/confMSG_Header"/>
</RelativeLayout>
<LinearLayout
android:id="@+id/rL02_ConfMSG"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal">
<TextView
android:id="@+id/confMSG_Yes"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:drawableRight="@drawable/accept"/>
</LinearLayout>
private void showConfirmation() {
// TODO Auto-generated method stubfin
TextView tv = (TextView) findViewById(R.id.confMSG_Yes);
tv.setText("some text");
}
听起来你的视图并没有扩大这个布局this.findViewById
基本上是在为this
视图而膨胀的布局中进行搜索
您可能需要在视图的构造函数中添加一行,如下所示(注意:是视图
类中的静态方法):
您从哪里调用showConfirmation()
?有可能是在布局膨胀之前调用它
初始化视图时,从XML中将其膨胀并返回对视图的引用:
视图=充气(getContext(),R.layout.layout_id,null)
然后获取对TextView的引用:
TextView tv = (TextView) view.findViewById(R.id.confMSG_Yes);
我从ontouchevent()调用上述方法。在构建视图的过程中,是否对布局进行了膨胀?如果不这样做,通过上面的代码,将解决你的问题。你应该考虑在别处推广你的布局。在onSizeChanged中这样做并不常见——通常,在onSizeChanged中,您希望将逻辑放在与宽度和高度更改相关的位置,而不是放在初始化视图的逻辑上。初始化更适合于中这样的构造函数。正如@gmale提到的,应该在视图构造函数中扩展布局XML,而不是在onSizechanged中。