1

我有代码:

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
4

1 回答 1

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);
           }
    }

主要:

setPrimaryFields(this);

PrimaryFieldsView 类不必扩展任何东西。

于 2013-10-27T20:55:03.637 回答