使用getLayoutParams()

时间:2016-02-07 00:25:28

标签: android nullpointerexception layoutparams

我有一个自定义的ImageView类(我不认为类中的代码很重要,但无论如何我都会将它包含在这里):

    package com.example.vroy.customcirclebuttontest;

import android.content.Context;
import android.graphics.Canvas;
import android.util.AttributeSet;
import android.util.Log;
import android.widget.ImageView;

public class CircleButton extends ImageView {`

private  int radius;
private  int x;
private  int y;

public CircleButton(Context context) {
    super(context);
    constructorTask();
}

public CircleButton(Context context, AttributeSet attrs) {
    super(context, attrs);
    constructorTask();
}

public CircleButton(Context context, AttributeSet attrs, int defStyleAttr) {
    super(context, attrs, defStyleAttr);
    constructorTask();
}

public CircleButton(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
    super(context, attrs, defStyleAttr, defStyleRes);
    constructorTask();
}


private void constructorTask() {
    x = 300;
    y = 300;
    radius = 100;
}

@Override
public void setPressed(boolean pressed) {
    super.setPressed(pressed);
    Log.i("Button Logger","Button Pressed");
}

@Override
protected  void onDraw(Canvas canvas) {
    super.onDraw(canvas);
    canvas.drawCircle(x, y, radius, GameView.green);
    Log.i("Drawing status", "CircleButton Drawing..." + " " + Integer.toString(this.x) + "," + Integer.toString(this.y));
}

}

我在我的活动中声明了这个类的一个实例:

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    testCircleButton = new CircleButton(getApplicationContext());
    makeFullScreen();

   testCircleButton.getLayoutParams().width = 200;
   testCircleButton.getLayoutParams().height = 200;

    RelativeLayout screenLayout = (RelativeLayout) findViewById(R.id.screenLayout);
    screenLayout.addView(testCircleButton);

    Log.i("Button Status","Adding Button To Layout");
}

然而,当我这样做时,我得到一个"空指针"异常。

我该如何解决这个问题?

1 个答案:

答案 0 :(得分:2)

这是因为您的testCircleButton未附加到活动中。如果它没有添加到任何父级,它没有LayoutParams。 使用

LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(200, 200) // I'm not sure about constructor arguments.
testCircleButton.setLayoutParams(lp);

如果您的根布局不同(FrameLayout等),请使用不同的LayoutParams。