gpt4 book ai didi

java - 尝试使用单独的类初始化 Android 中的小部件,收到 NullPointerException

转载 作者:行者123 更新时间:2023-12-01 04:23:57 25 4
gpt4 key购买 nike

我正在尝试将应用程序中的逻辑拉入一个单独的类中,以重用应用程序中的逻辑,但我不确定我想要做的是否可行。我知道我需要调用 PercentageCalc.java 中的 setContentView 函数以使值不为空,但是有什么方法可以在 Keypad 类中传递它吗?

NullPointerException 出现在 Keypad 类的第一行。

PercentageCalc.java

Keypad keypad = new Keypad();

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.percentage_calc);

/** Initialize variables for widget handles */
...
keypad.initializeWidgets();
}

Keypad.java

Button button_1, button_2, button_3, button_4, button_5, button_6, button_7, button_8,
button_9, button_0, button_clr, button_del, button_period;

public void initializeWidgets()
{
button_1 = (Button)findViewById(R.id.b_1);
button_2 = (Button)findViewById(R.id.b_2);
button_3 = (Button)findViewById(R.id.b_3);
button_4 = (Button)findViewById(R.id.b_4);
button_5 = (Button)findViewById(R.id.b_5);
button_6 = (Button)findViewById(R.id.b_6);
button_7 = (Button)findViewById(R.id.b_7);
button_8 = (Button)findViewById(R.id.b_8);
button_9 = (Button)findViewById(R.id.b_9);
button_clr = (Button)findViewById(R.id.b_clr);
button_0 = (Button)findViewById(R.id.b_0);
button_del = (Button)findViewById(R.id.b_del);
button_period = (Button)findViewById(R.id.b_period);
}

最佳答案

正确的方法是 tyczj 在评论中提到的。但是您可以将包含按钮的主视图(代码 fragment 中的 R.id.percentage_calc_container)传递给 Keypad 中的initializeWidgets() 方法,然后在其上调用 findViewById() 。

PercentageCalc.java

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.percentage_calc);

/** Initialize variables for widget handles */
...
View v = findViewById(R.id.percentage_calc_container);
keypad.initializeWidgets();
}

Keypad.java

public void initializeWidgets(View v)
{
button_1 = (Button)v.findViewById(R.id.b_1);
button_2 = (Button)v.findViewById(R.id.b_2);
button_3 = (Button)v.findViewById(R.id.b_3);
button_4 = (Button)v.findViewById(R.id.b_4);
button_5 = (Button)v.findViewById(R.id.b_5);
button_6 = (Button)v.findViewById(R.id.b_6);
button_7 = (Button)v.findViewById(R.id.b_7);
button_8 = (Button)v.findViewById(R.id.b_8);
button_9 = (Button)v.findViewById(R.id.b_9);
button_clr = (Button)v.findViewById(R.id.b_clr);
button_0 = (Button)v.findViewById(R.id.b_0);
button_del = (Button)v.findViewById(R.id.b_del);
button_period = (Button)v.findViewById(R.id.b_period);
}

关于java - 尝试使用单独的类初始化 Android 中的小部件,收到 NullPointerException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18660133/

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