I have two surfaceView, only one of them added to the view hierachy at a time, the other one is removed, my problem is, when an surfaceView added, there's a instant black rect cover it, can I avoid this?
here's the testing code:
public class MainActivity extends Activity {
private SurfaceView mSurfaceView;
private SurfaceView mSurfaceView1;
private SurfaceHolder.Callback mSurfaceCallback;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
View rv = this.getWindow().getDecorView();
final FrameLayout frameLayout = (FrameLayout) this.getWindow().getDecorView()
.findViewById(android.R.id.content);
final LinearLayout ll = new LinearLayout(this);
mSurfaceView = new SurfaceView(this);
mSurfaceView1= new SurfaceView(this);
mSurfaceCallback = new SurfaceHolder.Callback() {
#Override
public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {}
#Override
public void surfaceCreated(SurfaceHolder holder) {
Canvas c = null;
try
{
c = holder.lockCanvas();
c.drawColor(Color.GREEN);
Paint p = new Paint();
p.setColor(Color.WHITE);
Rect r = new Rect(100, 50, 300, 250);
c.drawRect(r, p);
} catch (Exception e) {
e.printStackTrace();
} finally {
if (c != null)
{
holder.unlockCanvasAndPost(c);
}
}
}
#Override
public void surfaceDestroyed(SurfaceHolder holder) {}
};
mSurfaceView.getHolder().addCallback(mSurfaceCallback);
mSurfaceView1.getHolder().addCallback(mSurfaceCallback);
Button b = new Button(this);b.setText("view1");
Button c = new Button(this);c.setText("view2");
b.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
try{
ll.addView(mSurfaceView);
ll.removeView(mSurfaceView1);
}catch(Exception e) {}
}
});
c.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
try{
ll.addView(mSurfaceView1);
ll.removeView(mSurfaceView);
}catch(Exception e) {}
}
});
ll.setOrientation(LinearLayout.VERTICAL);
ll.addView(b, new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT));
ll.addView(c, new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT));
frameLayout.addView(ll);
}
}
I think you can add the two surfaceviews when you call onCreate, and switch their status in onClick. like this:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
View rv = this.getWindow().getDecorView();
final FrameLayout frameLayout = (FrameLayout) this.getWindow().getDecorView()
.findViewById(android.R.id.content);
final LinearLayout ll = new LinearLayout(this);
mSurfaceView = new SurfaceView(this);
mSurfaceView1= new SurfaceView(this);
mSurfaceCallback = new SurfaceHolder.Callback() {
#Override
public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {}
#Override
public void surfaceCreated(SurfaceHolder holder) {
Canvas c = null;
try
{
c = holder.lockCanvas();
c.drawColor(Color.GREEN);
Paint p = new Paint();
p.setColor(Color.WHITE);
Rect r = new Rect(100, 50, 300, 250);
c.drawRect(r, p);
} catch (Exception e) {
e.printStackTrace();
} finally {
if (c != null)
{
holder.unlockCanvasAndPost(c);
}
}
}
#Override
public void surfaceDestroyed(SurfaceHolder holder) {}
};
mSurfaceView.getHolder().addCallback(mSurfaceCallback);
mSurfaceView1.getHolder().addCallback(mSurfaceCallback);
Button b = new Button(this);b.setText("view1");
Button c = new Button(this);c.setText("view2");
b.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
try{
// ll.addView(mSurfaceView);
// ll.removeView(mSurfaceView1);
mSurfaceView.setVisibility(View.VISIBLE);
mSurfaceView1.setVisibility(View.INVISIBLE);
}catch(Exception e) {}
}
});
c.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
try{
// ll.addView(mSurfaceView1);
// ll.removeView(mSurfaceView);
mSurfaceView1.setVisibility(View.VISIBLE);
mSurfaceView.setVisibility(View.INVISIBLE);
}catch(Exception e) {}
}
});
ll.setOrientation(LinearLayout.VERTICAL);
ll.addView(b, new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT));
ll.addView(c, new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT));
// add mSurfaceView & mSurfaceView1
ll.addView(mSurfaceView);
ll.addView(mSurfaceView1);
mSurfaceView.setVisibility(View.INVISIBLE);
mSurfaceView1.setVisibility(View.INVISIBLE);
frameLayout.addView(ll);
}
Related
In my program, the basic is:-
When the program open it will show an animation then it will show pie chart result.
my code is:---
public class Popup_animation11 extends Activity {
private static int[] COLORS = new int[] { Color.MAGENTA, Color.CYAN };
LinearLayout layout;
private CategorySeries mSeries = new CategorySeries("");
private DefaultRenderer mRenderer = new DefaultRenderer();
private GraphicalView mChartView;
Context ctx;
private TransparentProgressDialog pd;
private Handler h;
private Runnable r;
EditText name1,name2;
private int[] VALUES = { 40, 60 };
String x1,y1;
Button btnOpenPopup;
String[] NAME_LIST ;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.popup_main);
Button btnOpenPopup = (Button)findViewById(R.id.openpopup);
btnOpenPopup.setOnClickListener(new Button.OnClickListener(){
#Override
public void onClick(View arg0) {
pd.show();
}
});
h = new Handler();
pd = new TransparentProgressDialog(this, R.drawable.uktrafficlights);
r =new Runnable() {
#Override
public void run() {
if (pd.isShowing()) {
pd.dismiss();
}
}
};
}
#Override
protected void onDestroy() {
h.removeCallbacks(r);
if (pd.isShowing() ) {
pd.dismiss();
}
super.onDestroy();
}
private class TransparentProgressDialog extends Dialog {
private ImageView iv;
public TransparentProgressDialog(Context context, int resourceIdOfImage) {
super(context, R.style.TransparentProgressDialog);
WindowManager.LayoutParams wlmp = getWindow().getAttributes();
wlmp.gravity = Gravity.CENTER_HORIZONTAL;
getWindow().setAttributes(wlmp);
setTitle(null);
setCancelable(false);
setOnCancelListener(null);
LinearLayout layout = new LinearLayout(context);
layout.setOrientation(LinearLayout.VERTICAL);
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);
iv = new ImageView(context);
iv.setImageResource(resourceIdOfImage);
layout.addView(iv, params);
addContentView(layout, params);
}
#Override
public void show() {
super.show();
RotateAnimation anim = new RotateAnimation(0.0f, 360.0f , Animation.RELATIVE_TO_SELF, .5f, Animation.RELATIVE_TO_SELF, .5f);
anim.setInterpolator(new LinearInterpolator());
anim.setRepeatCount(Animation.INFINITE);
anim.setDuration(3000);
iv.setAnimation(anim);
iv.startAnimation(anim);
anim.setAnimationListener(new Animation.AnimationListener() {
#Override
public void onAnimationStart(Animation animation) {
}
#Override
public void onAnimationEnd(Animation animation) {
//here display data
mRenderer.setApplyBackgroundColor(true);
mRenderer.setBackgroundColor(Color.argb(100, 50, 50, 50));
mRenderer.setChartTitleTextSize(20);
mRenderer.setLabelsTextSize(15);
mRenderer.setLegendTextSize(15);
mRenderer.setMargins(new int[] { 20, 30, 15, 0 });
mRenderer.setZoomButtonsVisible(true);
mRenderer.setStartAngle(90);
mChartView = ChartFactory.getPieChartView(ctx, mSeries, mRenderer);
LayoutInflater layoutInflater = (LayoutInflater)getBaseContext() .getSystemService(LAYOUT_INFLATER_SERVICE);
View popupView = layoutInflater.inflate(R.layout.main_piechart, null);
final PopupWindow popupWindow = new PopupWindow( popupView, LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT);
layout = (LinearLayout)popupView.findViewById(R.id.chart);
layout.addView(mChartView);
name1=(EditText) findViewById(R.id.ext1);
name2=(EditText) findViewById(R.id.ext2);
x1=name1.getText().toString();
y1=name2.getText().toString();
NAME_LIST = new String[] { x1 , y1 };
for (int i = 0; i < VALUES.length; i++) {
mSeries.add(NAME_LIST[i] + "(" + VALUES[i]+"%)", VALUES[i]);
SimpleSeriesRenderer renderer = new SimpleSeriesRenderer();
renderer.setColor(COLORS[(mSeries.getItemCount() - 1) % COLORS.length]);
mRenderer.addSeriesRenderer(renderer);
}
if (mChartView != null) {
mChartView.repaint();
}
Button btnDismiss = (Button)popupView.findViewById(R.id.dismiss);
btnDismiss.setOnClickListener(new Button.OnClickListener(){
#Override
public void onClick(View v) {
popupWindow.dismiss();
}});
popupWindow.showAsDropDown(btnOpenPopup, 50, -30);
}
#Override
public void onAnimationRepeat(Animation animation) {
// TODO Auto-generated method stub
}
});
}
}
}
But the problem is when I open the program, animation is running and running.the result is not coming.
I requirement was first animation then the result..But only animation is running.. Where is the problem in my code? thanks in advance
my edited code is:---
public class Popup_animation11 extends Activity {
private static int[] COLORS = new int[] { Color.MAGENTA, Color.CYAN };
LinearLayout layout;
private CategorySeries mSeries = new CategorySeries("");
private DefaultRenderer mRenderer = new DefaultRenderer();
private GraphicalView mChartView;
Context ctx;
private TransparentProgressDialog pd;
private Handler h;
private Runnable r;
EditText name1,name2;
private int[] VALUES = { 40,60 };
String x1,y1;
Button btnOpenPopup;
String[] NAME_LIST ;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.popup_main);
Button btnOpenPopup = (Button)findViewById(R.id.openpopup);
btnOpenPopup.setOnClickListener(new Button.OnClickListener(){
#Override
public void onClick(View arg0) {
pd.show();
}
});
h = new Handler();
pd = new TransparentProgressDialog(this, R.drawable.uktrafficlights);
r =new Runnable() {
#Override
public void run() {
if (pd.isShowing()) {
pd.dismiss();
}
}
};
}
#Override
protected void onDestroy() {
h.removeCallbacks(r);
if (pd.isShowing() ) {
pd.dismiss();
}
super.onDestroy();
}
private class TransparentProgressDialog extends Dialog {
private ImageView iv;
public TransparentProgressDialog(Context context, int resourceIdOfImage) {
super(context, R.style.TransparentProgressDialog);
WindowManager.LayoutParams wlmp = getWindow().getAttributes();
wlmp.gravity = Gravity.CENTER_HORIZONTAL;
getWindow().setAttributes(wlmp);
setTitle(null);
setCancelable(false);
setOnCancelListener(null);
LinearLayout layout = new LinearLayout(context);
layout.setOrientation(LinearLayout.VERTICAL);
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);
iv = new ImageView(context);
iv.setImageResource(resourceIdOfImage);
layout.addView(iv, params);
addContentView(layout, params);
}
#Override
public void show() {
super.show();
RotateAnimation anim = new RotateAnimation(0.0f, 360.0f , Animation.RELATIVE_TO_SELF, .5f, Animation.RELATIVE_TO_SELF, .5f);
anim.setInterpolator(new LinearInterpolator());
anim.setRepeatCount(Animation.INFINITE);
anim.setDuration(3000);
iv.setAnimation(anim);
iv.startAnimation(anim);
anim.setAnimationListener(new Animation.AnimationListener() {
#Override
public void onAnimationStart(Animation animation) {
}
#Override
public void onAnimationEnd(Animation animation) {
//here display data
h.postDelayed(r, 100);
pd.dismiss();
mRenderer.setApplyBackgroundColor(true);
mRenderer.setBackgroundColor(Color.argb(100, 50, 50, 50));
mRenderer.setChartTitleTextSize(20);
mRenderer.setLabelsTextSize(15);
mRenderer.setLegendTextSize(15);
mRenderer.setMargins(new int[] { 20, 30, 15, 0 });
mRenderer.setZoomButtonsVisible(true);
mRenderer.setStartAngle(90);
mChartView = ChartFactory.getPieChartView(ctx, mSeries, mRenderer);
LayoutInflater layoutInflater = (LayoutInflater)getBaseContext() .getSystemService(LAYOUT_INFLATER_SERVICE);
View popupView = layoutInflater.inflate(R.layout.main_piechart, null);
final PopupWindow popupWindow = new PopupWindow( popupView, LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT);
layout = (LinearLayout)popupView.findViewById(R.id.chart);
layout.addView(mChartView);
name1=(EditText) findViewById(R.id.ext1);
name2=(EditText) findViewById(R.id.ext2);
x1=name1.getText().toString();
y1=name2.getText().toString();
NAME_LIST = new String[] { x1 , y1 };
for (int i = 0; i < VALUES.length; i++) {
mSeries.add(NAME_LIST[i] + "(" + VALUES[i]+"%)", VALUES[i]);
SimpleSeriesRenderer renderer = new SimpleSeriesRenderer();
renderer.setColor(COLORS[(mSeries.getItemCount() - 1) % COLORS.length]);
mRenderer.addSeriesRenderer(renderer);
}
if (mChartView != null) {
mChartView.repaint();
}
Button btnDismiss = (Button)popupView.findViewById(R.id.dismiss);
btnDismiss.setOnClickListener(new Button.OnClickListener(){
#Override
public void onClick(View v) {
popupWindow.dismiss();
}});
popupWindow.showAsDropDown(btnOpenPopup, 50, -30);
}
#Override
public void onAnimationRepeat(Animation animation) {
// TODO Auto-generated method stub
}
});
}
}
}
Try call anim.setAnimationListener() before call iv.startAnimation(anim);
I have a camera app in android. There is a image view and two button. When i am in landscape mode two button will be available on the image view and when i am in portrait mode buttons have to hidden and the aspect ratio will be right.
public class CustomCameraActivity extends Activity implements SurfaceHolder.Callback {
Camera camera;
SurfaceView surfaceView;
SurfaceHolder surfaceHolder;
boolean previewing = false;
LayoutInflater controlInflater = null;
Context context;
ImageView imageView;
SensorManager sensorManager;
float[] mGravs = new float[3];
float[] mGeoMags = new float[3];
float[] mRotationM = new float[16];
float[] mInclinationM = new float[16];
float[] mOrientation = new float[3];
float[] mOldOreintation = new float[3];
String[] mAccelerometer = new String[3];
String[] mMagnetic = new String[3];
String[] mRotation = new String[16];
String[] mInclination = new String[16];
String[] mOrientationString = new String[3];
String[] mOldOreintationString = new String[3];
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.main);
context = this;
sensorManager = (SensorManager)getSystemService(SENSOR_SERVICE);
//setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
imageView = (ImageView)findViewById(R.id.imgError);
getWindow().setFormat(PixelFormat.UNKNOWN);
surfaceView = (SurfaceView)findViewById(R.id.camerapreview);
surfaceHolder = surfaceView.getHolder();
surfaceHolder.addCallback(this);
surfaceHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
controlInflater = LayoutInflater.from(getBaseContext());
View viewControl = controlInflater.inflate(R.layout.custom, null);
LayoutParams layoutParamsControl = new LayoutParams(LayoutParams.FILL_PARENT,
LayoutParams.FILL_PARENT);
Button btn1 = (Button)viewControl.findViewById(R.id.Button01);
Button btn2 = (Button)viewControl.findViewById(R.id.Button02);
btn1.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
//Toast.makeText(context, "1111111111111111111111111", Toast.LENGTH_SHORT).show();
camera.takePicture(null, null, mPicture);
Constant.rotationValueForCamera = Constant.rotationValue;
}
});
btn2.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
//Toast.makeText(context, "22222222222222222222222222", Toast.LENGTH_SHORT).show();
Log.e("0 imagePickerStatus", Constant.imagePickerStatus+"");
Constant.imagePickerStatus = 0;
Log.e("0 imagePickerStatus", Constant.imagePickerStatus+"");
finish();
}
});
this.addContentView(viewControl, layoutParamsControl);
int ot = getResources().getConfiguration().orientation;
if(Configuration.ORIENTATION_LANDSCAPE == ot)
{
imageView.setVisibility(View.GONE);
Log.e("ori1111", "land");
}
else
{
imageView.setVisibility(View.VISIBLE);
Log.e("ori111", "port");
}
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
// Checks the orientation of the screen
if (newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE) {
//Toast.makeText(this, "landscape", Toast.LENGTH_SHORT).show();
imageView.setVisibility(View.GONE);
Log.e("ori", "land");
} else if (newConfig.orientation == Configuration.ORIENTATION_PORTRAIT){
//Toast.makeText(this, "portrait", Toast.LENGTH_SHORT).show();
imageView.setVisibility(View.VISIBLE);
Log.e("ori", "port");
}
}
public String getPollDeviceAttitude()
{
return Constant.rotationValueForCamera;
}
private SensorEventListener sensorEventListener = new SensorEventListener() {
public void onAccuracyChanged(Sensor sensor, int accuracy) {
}
/* Get the Sensors */
public void onSensorChanged(SensorEvent event) {
switch (event.sensor.getType()) {
case Sensor.TYPE_ACCELEROMETER:
System.arraycopy(event.values, 0, mGravs, 0, 3);
break;
case Sensor.TYPE_MAGNETIC_FIELD:
System.arraycopy(event.values, 0, mGeoMags, 0, 3);
break;
case Sensor.TYPE_ORIENTATION:
System.arraycopy(event.values, 0, mOldOreintation, 0, 3);
break;
default:
return;
}
// If mGravs and mGeoMags have values then find rotation matrix
if (mGravs != null && mGeoMags != null) {
// checks that the rotation matrix is found
boolean success = SensorManager.getRotationMatrix(mRotationM, mInclinationM, mGravs, mGeoMags);
if (success) {
/* getOrientation Values */
SensorManager.getOrientation(mRotationM, mOrientation);
for(int i=0; i<3; i++){
mAccelerometer[i] = Float.toString(mGravs[i]);
mMagnetic[i] = Float.toString(mGeoMags[i]);
mOrientationString[i] = Float.toString(mOrientation[i]);
mOldOreintationString[i] = Float.toString(mOldOreintation[i]);
}
/* Make everything text to show on device
TextView xaxisAccelerometerText = (TextView)findViewById(R.id.xaxisAccelerometer);
xaxisAccelerometerText.setText(mAccelerometer[0]);
TextView yaxisAccelerometerText = (TextView)findViewById(R.id.yaxisAccelerometer);
yaxisAccelerometerText.setText(mAccelerometer[1]);
TextView zaxisAccelerometerText = (TextView)findViewById(R.id.zaxisAccelerometer);
zaxisAccelerometerText.setText(mAccelerometer[2]);
TextView xaxisMagneticText = (TextView)findViewById(R.id.xaxisMagnetic);
xaxisMagneticText.setText(mMagnetic[0]);
TextView yaxisMagneticText = (TextView)findViewById(R.id.yaxisMagnetic);
yaxisMagneticText.setText(mMagnetic[1]);
TextView zaxisMagneticText = (TextView)findViewById(R.id.zaxisMagnetic);
zaxisMagneticText.setText(mMagnetic[2]);
TextView xaxisOrientationText = (TextView)findViewById(R.id.xaxisOrientation);
xaxisOrientationText.setText(mOrientationString[0]);
TextView yaxisOrientationText = (TextView)findViewById(R.id.yaxisOrientation);
yaxisOrientationText.setText(mOrientationString[1]);
TextView zaxisOrientationText = (TextView)findViewById(R.id.zaxisOrientation);
zaxisOrientationText.setText(mOrientationString[2]);
TextView xaxisOldOrientationText = (TextView)findViewById(R.id.xaxisOldOrientation);
xaxisOldOrientationText.setText(mOldOreintationString[0]);
TextView yaxisOldOrientationText = (TextView)findViewById(R.id.yaxisOldOrientation);
yaxisOldOrientationText.setText(mOldOreintationString[1]);
TextView zaxisOldOrientationText = (TextView)findViewById(R.id.zaxisOldOrientation);
zaxisOldOrientationText.setText(mOldOreintationString[2]);*/
Constant.rotationValue = mOrientationString[0] + " " + mOrientationString[1] + " " + mOrientationString[2];
}else{
/* Make everything text to show on device even if getRotationMatrix fails
String matrixFailed = "Rotation Matrix Failed";
TextView xaxisAccelerometerText = (TextView)findViewById(R.id.xaxisAccelerometer);
xaxisAccelerometerText.setText(mAccelerometer[0]);
TextView yaxisAccelerometerText = (TextView)findViewById(R.id.yaxisAccelerometer);
yaxisAccelerometerText.setText(mAccelerometer[1]);
TextView zaxisAccelerometerText = (TextView)findViewById(R.id.zaxisAccelerometer);
zaxisAccelerometerText.setText(mAccelerometer[2]);
TextView xaxisMagneticText = (TextView)findViewById(R.id.xaxisMagnetic);
xaxisMagneticText.setText(mMagnetic[0]);
TextView yaxisMagneticText = (TextView)findViewById(R.id.yaxisMagnetic);
yaxisMagneticText.setText(mMagnetic[1]);
TextView zaxisMagneticText = (TextView)findViewById(R.id.zaxisMagnetic);
zaxisMagneticText.setText(mMagnetic[2]);
TextView xaxisOrientationText = (TextView)findViewById(R.id.xaxisOrientation);
xaxisOrientationText.setText(matrixFailed);
TextView yaxisOrientationText = (TextView)findViewById(R.id.yaxisOrientation);
yaxisOrientationText.setText(matrixFailed);
TextView zaxisOrientationText = (TextView)findViewById(R.id.zaxisOrientation);
zaxisOrientationText.setText(matrixFailed);
TextView xaxisOldOrientationText = (TextView)findViewById(R.id.xaxisOldOrientation);
xaxisOldOrientationText.setText(mOldOreintationString[0]);
TextView yaxisOldOrientationText = (TextView)findViewById(R.id.yaxisOldOrientation);
yaxisOldOrientationText.setText(mOldOreintationString[1]);
TextView zaxisOldOrientationText = (TextView)findViewById(R.id.zaxisOldOrientation);
zaxisOldOrientationText.setText(mOldOreintationString[2]);*/
Constant.rotationValue = mOrientationString[0] + " " + mOrientationString[1] + " " + mOrientationString[2];
}
}
}
};
protected void onPause()
{
super.onPause();
sensorManager.unregisterListener(sensorEventListener);
}
#Override
public void onResume()
{
super.onResume();
sensorManager.registerListener(sensorEventListener, sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER), SensorManager.SENSOR_DELAY_NORMAL);
sensorManager.registerListener(sensorEventListener, sensorManager.getDefaultSensor(Sensor.TYPE_MAGNETIC_FIELD), SensorManager.SENSOR_DELAY_NORMAL);
sensorManager.registerListener(sensorEventListener, sensorManager.getDefaultSensor(Sensor.TYPE_ORIENTATION), SensorManager.SENSOR_DELAY_NORMAL);
if(Constant.isCapturedOk)
{
Constant.isCapturedOk = false;
finish();
}
}
PictureCallback mPicture = new PictureCallback() {
#Override
public void onPictureTaken(byte[] data, Camera camera) {
Log.e("Camrera", "22222222222222222");
Intent intent = new Intent(context, PreviewActivity.class);
//intent.putExtra("data", data);
Constant.imageData = data;
startActivity(intent);
}
};
#Override
public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
if(previewing){
camera.stopPreview();
previewing = false;
}
if (camera != null){
try {
camera.setPreviewDisplay(surfaceHolder);
camera.startPreview();
previewing = true;
} catch (Exception e) {
e.printStackTrace();
}
}
}
#Override
public void surfaceCreated(SurfaceHolder holder) {
camera = Camera.open();
}
#Override
public void surfaceDestroyed(SurfaceHolder holder) {
camera.stopPreview();
camera.release();
camera = null;
previewing = false;
}
#Override
protected void onStop()
{
super.onStop();
Log.e("Tab", "Stoping");
}
#Override
public boolean onKeyDown(int keyCode,KeyEvent event)
{
if(keyCode==KeyEvent.KEYCODE_BACK)
{
return true;
}
return super.onKeyDown(keyCode, event);
}
}
create different layouts for portrait and landscape
like this:
http://mdaslam.wordpress.com/2013/01/15/android-programming-screen-orientationportrait-landscape/
and change visibility of button in other layout using this:
android:visibility="invisible"
your problem would surely be solved.
I'm current creating a game and i've made 3 main classes - GameView (which extends surfaceview), GameViewThread (which is a thread used for surfaceview) and a MainActivity.
I want to enter a background image in SurfaceView, but have not been able to figure out how to do so.
Using setBackground() in the onDraw method of GameView doesn't work as well.
I would greatly appreciate any help you guys can provide me with.
Here is my GameView class:
public class GameView extends SurfaceView implements SurfaceHolder.Callback {
private Bitmap bmp1;
private SurfaceHolder holder;
private GameLoopThread gameLoopThread;
private Sprite sprite;
private float sensorX = 0;
private Platform platform[] = new Platform[7];
private Bonus GravUp[] = new Bonus[3];
private Bonus GravDown[] = new Bonus[3];
private Bitmap bmp2;
private Bitmap bmp3;
private boolean collision;
private int a;
private int b;
private int c1;
private double c2;
int agility = 50;
private Bitmap bmp4;
public double getsensorX() {
return sensorX;
}
public double setsensorX(float s) {
return sensorX = s;
}
synchronized public int getSpriteY() {
return sprite.y;
}
synchronized public int getSpriteX() {
return sprite.x;
}
synchronized public int getSpriteHeight() {
return sprite.height;
}
synchronized public int getSpriteWidth() {
return sprite.width;
}
public GameView(Context context) {
super(context);
gameLoopThread = new GameLoopThread(this);
holder = getHolder();
holder.addCallback(this);
bmp1 = BitmapFactory.decodeResource(getResources(), R.drawable.russel);
sprite = new Sprite(this);
sprite.getBMP(bmp1);
bmp2 = BitmapFactory.decodeResource(getResources(), R.drawable.brick);
bmp3 = BitmapFactory.decodeResource(getResources(), R.drawable.gravup);
bmp4 = BitmapFactory.decodeResource(getResources(), R.drawable.gravdown);
for (int i = 0; i < GravUp.length; i++) {
GravUp[i] = new Bonus(this, bmp3);
}
for (int i = 0; i < GravDown.length; i++) {
GravDown[i] = new Bonus(this, bmp4);
}
for (int i = 0; i < platform.length; i++) {
Random r = new Random();
platform[i] = new Platform(this, bmp2, 850 + 200 * i,
400 - r.nextInt(250));
}
}
#Override
public void surfaceDestroyed(SurfaceHolder holder) {
boolean retry = true;
gameLoopThread.setRunning(false);
while (retry) {
try {
gameLoopThread.join();
retry = false;
} catch (InterruptedException e) {
}
}
}
#Override
public void surfaceCreated(SurfaceHolder holder) {
gameLoopThread.setRunning(true);
gameLoopThread.start();
}
#Override
public void surfaceChanged(SurfaceHolder holder, int format, int width,
int height) {
}
#Override
protected void onDraw(Canvas canvas) {
canvas.drawColor(Color.YELLOW);
sprite.Draw(canvas);
for (int i = 0; i < platform.length; i++) {
platform[i].Draw(canvas);
}
for (int i = 0; i < GravUp.length; i++) {
GravUp[i].Draw(canvas);
}
for (int i = 0; i < GravDown.length; i++) {
GravDown[i].Draw(canvas);
}
}
My MainActivity Class:
public class MainActivity extends Activity {
GameView gameView;
FrameLayout game;
RelativeLayout GameButtons;
Button butOne;
Button butTwo;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
gameView = new GameView(this);
game = new FrameLayout(this);
GameButtons = new RelativeLayout(this);
RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(
RelativeLayout.LayoutParams.MATCH_PARENT,
RelativeLayout.LayoutParams.MATCH_PARENT);
GameButtons.setLayoutParams(params);
game.addView(gameView);
game.addView(GameButtons);
setContentView(game);
}
}
How can I use an image I have saved in res/drawable-hdpi folder as the background to my game?
Should I use the command in GameView or MainActivity?
Do let me know if you need more information in order to help me out!
Thank you
i am using a surface view to draw interactive piechart. here is my code which will looks like all surface view examples.
class PieChart extends SurfaceView implements SurfaceHolder.Callback {
public PieChart(Context context) {
super(context);
// Log.i("PieChart", "PieChart : constructor");
getHolder().addCallback(this);
}
#Override
public void onDraw(Canvas canvas) {
if (hasData) {
resetColor();
try {
canvas.drawColor(getResources().getColor(R.color.graphbg_color));
graphDraw(canvas);
} catch (ValicException ex) {
}
}
}
#Override
public void surfaceChanged(SurfaceHolder holder, int format, int width,
int height) {
Log.i("PieChart", "surfaceChanged");
}
public int callCount = 0;
#Override
public void surfaceCreated(SurfaceHolder holder) {
try {
// Log.i("PieChart", "surfaceCreated");
mChartThread = new ChartThread(getHolder(), this);
mChartThread.setRunning(true);
if (!mChartThread.isAlive()) {
mChartThread.start();
}
Rect mFrame = holder.getSurfaceFrame();
mOvalF = new RectF(0, 0, mFrame.right, mFrame.right);
} catch (Exception e) {
// No error message required
}
}
#Override
public void surfaceDestroyed(SurfaceHolder holder) {
// Log.i("PieChart", "surfaceDestroyed");
boolean retry = true;
callCount = 0;
mChartThread.setRunning(false);
while (retry) {
try {
mChartThread.join();
retry = false;
} catch (InterruptedException e) {
// No error message required
}
}
}
}
class ChartThread extends Thread {
private SurfaceHolder mSurfaceHolder;
private PieChart mPieChart;
private boolean mRefresh = false;
public ChartThread(SurfaceHolder surfaceHolder, PieChart pieChart) {
// Log.i("ChartThread", "ChartThread");
mSurfaceHolder = surfaceHolder;
mPieChart = pieChart;
}
public void setRunning(boolean Refresh) {
// Log.i("ChartThread", "setRunning : " + Refresh);
mRefresh = Refresh;
}
#Override
public void run() {
Canvas c;
// Log.i("ChartThread", "run : " + mRefresh);
while (mRefresh) {
c = null;
try {
c = mSurfaceHolder.lockCanvas(null);
// c.drawColor(0xFFebf3f5);
synchronized (mSurfaceHolder) {
mPieChart.onDraw(c);
}
} catch (Exception ex) {
} finally {
// do this in a finally so that if an exception is thrown
// during the above, we don't leave the Surface in an
// inconsistent state
if (c != null) {
mSurfaceHolder.unlockCanvasAndPost(c);
}
}
}
}
}
with this i am able to draw pie charts successfully. but here the issue is "before loading pie chart black rectangle is visible for a second which is surfaceview's default back ground". so I want to set background color for surface view to avoid the black rectangle.
The following is the changed code for drawing background color to surface view.
public PieChart(Context context) {
super(context);
// Log.i("PieChart", "PieChart : constructor");
getHolder().addCallback(this);
setBackgroundColor(getResources().getColor(R.color.graphbg_color));
}
#Override
public void onDraw(Canvas canvas) {
if (hasData) {
setBackgroundColor(getResources().getColor(R.color.graphbg_color));
resetColor();
try {
canvas.drawColor(getResources().getColor(R.color.graphbg_color));
graphDraw(canvas);
} catch (ValicException ex) {
}
}
}
with these changes, black rectangle issue is resolved. but piechart is not refreshing properly. can someone help me to resolve any of these two issues.
class PieChart extends SurfaceView implements SurfaceHolder.Callback {
private int backGroundColor = Color.BLACK;
public PieChart(Context context,int backGroundColor) {
super(context);
setBackGroundColor(backGroundColor);
// Log.i("PieChart", "PieChart : constructor");
getHolder().addCallback(this);
}
public void setBackGroundColor(int color){
this.backGroundColor = color;
}
#Override
public void onDraw(Canvas canvas) {
Paint paint = new Paint();
paint.setStyle(Paint.Style.FILL_AND_STROKE);
paint.setStrokeWidth(3);
paint.setAntiAlias(true);
paint.setColor(backGroundColor);
canvas.drawRect(0, 0, this.getWidth(), this.getHeight(), paint);
if (hasData) {
resetColor();
try {
canvas.drawColor(getResources().getColor(R.color.graphbg_color));
graphDraw(canvas);
} catch (ValicException ex) {
}
}
}
#Override
public void surfaceChanged(SurfaceHolder holder, int format, int width,
int height) {
Log.i("PieChart", "surfaceChanged");
}
public int callCount = 0;
#Override
public void surfaceCreated(SurfaceHolder holder) {
try {
// Log.i("PieChart", "surfaceCreated");
mChartThread = new ChartThread(getHolder(), this);
mChartThread.setRunning(true);
if (!mChartThread.isAlive()) {
mChartThread.start();
}
Rect mFrame = holder.getSurfaceFrame();
mOvalF = new RectF(0, 0, mFrame.right, mFrame.right);
} catch (Exception e) {
// No error message required
}
}
#Override
public void surfaceDestroyed(SurfaceHolder holder) {
// Log.i("PieChart", "surfaceDestroyed");
boolean retry = true;
callCount = 0;
mChartThread.setRunning(false);
while (retry) {
try {
mChartThread.join();
retry = false;
} catch (InterruptedException e) {
// No error message required
}
}
}
}
class ChartThread extends Thread {
private SurfaceHolder mSurfaceHolder;
private PieChart mPieChart;
private boolean mRefresh = false;
public ChartThread(SurfaceHolder surfaceHolder, PieChart pieChart) {
// Log.i("ChartThread", "ChartThread");
mSurfaceHolder = surfaceHolder;
mPieChart = pieChart;
}
public void setRunning(boolean Refresh) {
// Log.i("ChartThread", "setRunning : " + Refresh);
mRefresh = Refresh;
}
#Override
public void run() {
Canvas c;
// Log.i("ChartThread", "run : " + mRefresh);
while (mRefresh) {
c = null;
try {
c = mSurfaceHolder.lockCanvas(null);
// c.drawColor(0xFFebf3f5);
synchronized (mSurfaceHolder) {
mPieChart.onDraw(c);
}
} catch (Exception ex) {
} finally {
// do this in a finally so that if an exception is thrown
// during the above, we don't leave the Surface in an
// inconsistent state
if (c != null) {
mSurfaceHolder.unlockCanvasAndPost(c);
}
}
}
}
}
and in yout class client you can use the setBackGroundColor(your color) ;)
Here is my main:
#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);
}
Here is my 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();
}
}
}
}
I have a secondCircle class that is the exact same as above with the name changed and the color of the circle being Red.
Here is my firstThread class:
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);
}
}
}
}
I have a secondThread class that is the same as above with a different name and that calls secondCircle's onDraw().
When i run this program it only shows the blue circle and not the red circle. Why is this?
when you add the views, add them with layout parameters. Its possible the 1st view is filling the parent, leaving no space for the second view.
you could do something like
LinearLayout.LayoutParams p = new LinearLayout.LayoutParams(
LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
layout.addView(first,p);
layout.addView(second,p);