这是我的主要内容:
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
LinearLayout layout = (LinearLayout) findViewById(R.id.mainView);
TextView text= (TextView) findViewById(R.id.text);
text.setText("This is a Test!");
firstCircle first = new firstCircle(this);
secondCircle second = new secondCircle(this);
layout.addView(first);
layout.addView(second);
}
这是我的firstCircleClass:
public class firstCircle extends SurfaceView implements SurfaceHolder.Callback {
private firstThread _firstThread;
private secondThread _secondThread;
private SurfaceHolder surfaceHolder;
public firstCircle (Context context, AttributeSet attrs){
super(context,attrs);
getHolder().addCallback(this);
setFocusable(true);
_firstThread= new firstThread(getHolder(),this);
}
public firstCircle (Context context){
super(context);
getHolder().addCallback(this);
setFocusable(true);
_firstThread= new firstThread(getHolder(),this);
}
@Override
public void onDraw(Canvas c){
String tag="My Activity";
Paint paint = new Paint();
paint.setColor(Color.BLUE);
c.drawCircle(100,100,100,paint);
}
@Override
public void surfaceCreated(SurfaceHolder holder){
_firstThread.setRunning(true);
_firstThread.start();
}
@Override
public void surfaceChanged(SurfaceHolder holder, int format, int width, int height){
}
@Override
public void surfaceDestroyed(SurfaceHolder holder){
boolean retry = true;
_firstThread.setRunning(false);
while (retry){
try{
_firstThread.join();
retry = false;
}catch (InterruptedException e){
e.printStackTrace();
}
}
}
}
我有一个secondCircle类与上面完全相同,名称已更改,圆圈的颜色为红色。
这是我的firstThread课程:
public class firstThread extends Thread {
private SurfaceHolder _surfaceHolder;
private firstClass _firstClass;
private boolean _run = false;
public firstThread (SurfaceHolder surfaceHolder, firstClass first){
_surfaceHolder = surfaceHolder;
_firstClass= first;
}
public void setRunning (boolean run){
_run = run;
}
@Override
public void run(){
while(_run){
Canvas c=null;
try{
c = _surfaceHolder.lockCanvas(null);
synchronized(_surfaceHolder){
_firstThread.onDraw(c);
}
} finally {
}
if (c!=null){
_surfaceHolder.unlockCanvasAndPost(c);
}
}
}
}
我有一个secondThread类,它与上面的名字不同,并且调用了secondCircle的onDraw()。
当我运行此程序时,它只显示蓝色圆圈而不是红色圆圈。这是为什么?
答案 0 :(得分:1)
添加视图时,请使用布局参数添加视图。可能第一个视图正在填充父级,第二个视图没有空间。
你可以做点什么LinearLayout.LayoutParams p = new LinearLayout.LayoutParams(
LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
layout.addView(first,p);
layout.addView(second,p);