我有代码:
LinearLayout primaryFieldsView = (LinearLayout) findViewById(R.id.mainLayout);
for(int j=0; j<5; j++){
TextView text = new TextView(this);
text.setText("The Value of i is :"); // <-- does it really compile without the + sign?
text.setTextSize(12);
text.setGravity(Gravity.LEFT);
text.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT));
primaryFieldsView.addView(text);
}
我想这个代码是从另一个类调用的,例如: 在主要班级:
new PrimaryFieldsView().setPrimaryFields();
其他课程:
public class PrimaryFieldsView extends Activity{
public void setPrimaryFields(){
LinearLayout primaryFieldsView = (LinearLayout) findViewById(R.id.mainLayout);
for(int j=0; j<5; j++){
TextView text = new TextView(this);
text.setText("The Value of i is :"); // <-- does it really compile without the + sign?
text.setTextSize(12);
text.setGravity(Gravity.LEFT);
text.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT));
primaryFieldsView.addView(text);
}
}
当我把这段代码放在Main类中时:
LinearLayout primaryFieldsView = (LinearLayout) findViewById(R.id.mainLayout);
for(int j=0; j<5; j++){
TextView text = new TextView(this);
text.setText("The Value of i is :"); // <-- does it really compile without the + sign?
text.setTextSize(12);
text.setGravity(Gravity.LEFT);
text.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT));
primaryFieldsView.addView(text);
}
此刻我有错误
10-27 21:32:58.389: E/AndroidRuntime(2907): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.passreader/com.example.passreader.views.CouponView}: java.lang.NullPointerException
答案 0 :(得分:0)
public void setPrimaryFields(Activity activity)
{
LinearLayout primaryFieldsView = (LinearLayout) activity.findViewById(R.id.mainLayout);
for(int j=0; j<5; j++){
TextView text = new TextView(this);
text.setText("The Value of i is :"); // <-- does it really compile without the + sign?
text.setTextSize(12);
text.setGravity(Gravity.LEFT);
text.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT));
primaryFieldsView.addView(text);
}
}
在main中:
setPrimaryFields(this);
虽然PrimaryFieldsView类不必扩展任何内容。