我试图将我的应用程序中的逻辑拉到一个单独的类中,以重用我的应用程序中的逻辑,我不确定我想做什么是可能的。我知道我需要在PercentageCalc.java中调用setContentView函数,以使值不为null,但有没有办法在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);
}
答案 0 :(得分:0)
正确的方法是评论中提到的tyczj。但是你可以将包含按钮的主视图(片段中的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);
}