我試圖做一個簡單的應用程序,當一個按鈕被按下時繪製隨機的圓圈,並且當另一個按鈕被按下時將它們全部從屏幕清除。目前,當我由於某種原因,仿真器啓動應用程序啓動自動生成的圈子,那麼如果我試圖按按鈕,生成另一個圈子的應用程序崩潰,我在在android中生成隨機圓圈
c.drawcircle(b.getX(), b.getY(), b.getR(), p)
得到
NullPointerException異常
方法。
繼承人什麼我目前有:
主營:
import java.util.ArrayList;
import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.LinearLayout;
public class Bubbles extends Activity implements OnClickListener
{
Button b1,b2;
drawView dv;
LinearLayout frame;
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_bubbles);
dv = new drawView(getApplicationContext());
frame = (LinearLayout)findViewById(R.id.LinearLayout2);
b1 = (Button)findViewById(R.id.BubbleButton);
b1.setOnClickListener(this);
b2 = (Button)findViewById(R.id.ClearButton);
b2.setOnClickListener(this);
frame.addView(dv);
}
@Override
public void onClick(View v)
{
if(v==b1)
{
dv.onDraw(null);
}
if(v==b2)
{
dv.clear();
}
v.postInvalidate();
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.bubbles, menu);
return true;
}
}
drawView函數:
import java.util.ArrayList;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.view.View;
public class drawView extends View
{
ArrayList<Bubble> bList = new ArrayList<Bubble>();
Paint p = new Paint(Paint.ANTI_ALIAS_FLAG);
public drawView(Context con)
{
super(con);
}
public void onDraw(Canvas c)
{
Bubble b = new Bubble();
p.setColor(b.getColor());
p.setStyle(Paint.Style.FILL);
bList.add(b);
c.drawCircle(b.getX(), b.getY(), b.getR(), p);
}
public void clear()
{
bList.clear();
}
}
即時通訊使用的ArrayList這個類來存儲所有我做的氣泡,然後清除arrayList使用清除按鈕。 這裏是泡泡類我做了與它去:
泡泡:
import android.graphics.Color;
public class Bubble
{
int color;
int y;
int x;
int r;
public Bubble()
{
color = Color.rgb(rand(0,255), rand(0,255), rand(0,255));
r = rand(0,255);
x =rand(0,255);
y = rand(0,255);
}
public int getColor() {
return color;
}
public int getY() {
return y;
}
public int getX() {
return x;
}
public int getR() {
return r;
}
/******************************rand()*****************************/
public int rand(int a, int b)
{
return((int)((b-a+1)*Math.random() + a));
}
}
感謝您的任何投入,這是我第一次與圖形搞亂所以我不是100%肯定,爲什麼發生這種情況。
該行上的哪個變量爲空?使用調試器瀏覽代碼或添加一些日誌語句來弄清楚。 –