gpt4 book ai didi

android - 自定义小部件在 setRequestedViewSize 上抛出 NullPointerException

转载 作者:行者123 更新时间:2023-11-29 18:22:20 24 4
gpt4 key购买 nike

大家早上好

我正在开发一个 Android 应用程序,但遇到了一些问题。我创建了一个扩展 View 的新类。我已经覆盖了适当的方法(Constructor、onDraw、onMeasure)并通过应用程序布局 XML(称为 main.xml)实例化 View 。

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

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>

谢谢!山姆

最佳答案

问题出在我的小部件上,我有正确的构造函数(Context context AttributeSet attr);但是 - super(context) 被调用 - 而不是 super(context, attr)。 一旦我解决了这个问题,生活就变得更好了。

谢谢大家的信息!

关于android - 自定义小部件在 setRequestedViewSize 上抛出 NullPointerException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4736050/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com