2011-01-19 22 views
1

早上好乡亲一个NullPointerException,自定义部件抛出的setRequestedViewSize

我工作的一个Android应用程序,我已经遇到一个有点问题。我创建了一个扩展View的新类。我重写了适当的方法(构造函数,onDraw,onMeasure),并通过应用程序布局XML(称为main.xml)实例化视图。

在我的应用程序的源代码,我有以下代码:

public class CustomViewTest extends Activity { 
    /** Called when the activity is first created. */ 
    @Override 
    public void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 

/* I *think* I need to setContentView before I actually can use any of the widgets on the form. */ 
     setContentView(R.layout.main);  
     Button b = (Button)findViewById(R.id.button); 

     b.setOnClickListener(new OnClickListener() { 

    @Override 
    public void onClick(View v) { 
    // TODO Auto-generated method stub 
// my new widget 
newWidget s = (newWidget)findViewById(R.id.testWidget); 
s.setRequestedViewSize(300); 
    } 

     }); 


    } 
} 

这里的问题是,s.setRequestedViewSize(300)抛出一个NullPointerException。有没有人遇到过,或可以借给我一些建议?

[编辑] main.xml中看起来是这样的:

它返回null,但XML是这样的:

<?xml version="1.0" encoding="utf-8"?> 
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 
    android:orientation="vertical" 
    android:layout_width="fill_parent" 
    android:layout_height="fill_parent" 
    > 
    <com.testing.CustomViewTest02.newWidget 
     android:id="@+id/testWidget" 
     android:layout_width="fill_parent" 
     android:layout_height="fill_parent" /> 
    <Button android:id="@+id/button" 
      android:layout_width="wrap_content" 
      android:layout_height="wrap_content" 
      ></Button> 
</LinearLayout> 

谢谢你! 山姆

回答

2

的问题是在我的窗口小部件,我有正确的构造函数(上下文的背景下的AttributeSet attr)使用;但是 - super(context)被称为 - 而不是super(context, attr).一旦我解决这个问题,生活就会更好。

感谢您的信息大家!

1

你必须与R.id.testWidget ID没有观点:这不是关于非静态方法。由于findViewById()返回null,下一行将引发异常。

0

你引用您的main.xml中自定义视图? @Pontus是对的。没有视图从findViewById()方法返回。

如果在onCreate方法中调用构造函数,然后将其设置为可见或将其添加到另一个视图(无论您尝试使用它),那么最好在onCreate方法中引用它。按钮被点击。

编辑:根据你上面的XML。您的自定义类是否实现了一个带有Context和AttributeSet的构造函数?具有AttributeSet的构造函数是Android将调用来从XML布局创建类的构造函数。

+0

是的,这显示* *精细(我只是画就是查看不同的颜色暂时的,直到这个问题解决)。只有当我按下按钮时,我才会得到一个强制关闭。 – Sam 2011-01-19 14:20:21

相关问题