Hide ImageView when orientation is chaged - android

I'm trying to hide(ImageView.Gone) an image on my layout when the phone in landscape mode. I've tried:
this.imageView = (ImageView) findViewById(R.id.sheep_image);
this.myOrientationEventListener = new OrientationEventListener(this,
SensorManager.SENSOR_DELAY_NORMAL) {
#Override
public void onOrientationChanged(int orientation) {
editText.setHint("orientation changed");
if (orientation == Configuration.ORIENTATION_LANDSCAPE) {
imageView.setVisibility(ImageView.GONE);
} else {
imageView.setVisibility(ImageView.VISIBLE);
}
}
};
xml:
<ImageView
android:id="#+id/sheep_image"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:src="#drawable/pic"/>
but it doesn't seem to work. Nothing happens, not even the hint of the EditText.

Related

Rotating recyclerView at it's position to 90 degrees

I have screen where upper half is covered with the cameraView and bottom half is a slidingPanel which contains a fragment and the fragment contains a recyclerView. I want the screen to be portrait only but when the orientation changes to landscape the object should rotate to 90 degrees at its position. I am rotating the FrameLayout which is containing the Fragment and which contains the RecyclerView. The object rotates perfectly but the problem is recyclerView is behaving very strange. When the frameLayout rotated to 90 degrees RecyclerView instead of scrolling vertically in landscape mode it is scrolling when scroll horizontally.
Below is my XML containing the FrameLayout which is been rotated to 90 degree.
<com.sothree.slidinguppanel.SlidingUpPanelLayout
xmlns:sothree="http://schemas.android.com/apk/res-auto"
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/tools"
android:id="#+id/sliding_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="bottom"
sothree:umanoDragView="#+id/layout_dragger"
sothree:umanoPanelHeight="68dp"
sothree:umanoShadowHeight="4dp"
app:ignore="NamespaceTypo"
android:background="#color/transparent">
<com.otaliastudios.cameraview.CameraView
android:id="#+id/camera"
android:keepScreenOn="true"
android:layout_width="match_parent"
android:layout_height="match_parent"
sothree:cameraFacing="front"
sothree:cameraSessionType="video"/>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<LinearLayout
android:id="#+id/main_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:focusable="false"
android:orientation="vertical" >
<RelativeLayout
android:id="#+id/layout_dragger"
android:layout_width="match_parent"
android:layout_height="68dp">
<ImageView
android:id="#+id/up_arrow"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="#drawable/up_arrow"
android:layout_alignParentLeft="true"/>
<ImageView
android:id="#+id/record"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="#drawable/record"
android:layout_centerInParent="true"/>
</RelativeLayout>
<FrameLayout
android:id="#+id/frame_video"
android:layout_width="match_parent"
android:layout_height="250dp">
</FrameLayout>
</LinearLayout>
</LinearLayout>
</com.sothree.slidinguppanel.SlidingUpPanelLayout>
Below is my Class which contains the rotating animation.
public class MirrorFragment extends Fragment {
private LinearLayout mQueen;
private Button mHidden, accept, decline;
private static final String TAG = "DemoActivity";
private DraggingPanel mDraggingPanel;
private LinearLayout mMainLayout;
private FrameLayout frameContainer;
Fragment childFragment;
private Context mContext;
int height,width;
int draggingPanelHeight, draggingPanelWidth;
private ImageView iv_record, up_arrow;
RelativeLayout.LayoutParams param;
FrameLayout.LayoutParams frameParam;
SlidingUpPanelLayout mLayout;
private Animation toLandAnim, toPortAnim;
private OrientationListener orientationListener;
private CameraView cameraView;
private boolean mCapturingVideo =false;
Fragment fragment;
private static final String VIDEO_EXTENSION = ".mp4";
private String mNextVideoAbsolutePath;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_mirror, null);
}
#Override
public void onViewCreated(#NonNull View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
mContext = getContext();
fragment = (MirrorFragment)getFragmentManager().findFragmentByTag("mirror_frag");
initViews(view);
// setWidthOfBottomContainer();
up_arrow.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
}
});
iv_record.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(mCapturingVideo){
stopVideo();
}else{
captureVideo();
}
}
});
}
private void initViews(View view) {
mLayout = (SlidingUpPanelLayout) view.findViewById(R.id.sliding_layout);
mLayout.setAnchorPoint(0.5f);
mMainLayout = view.findViewById(R.id.main_layout);
frameContainer = view.findViewById(R.id.frame_video);
cameraView = view.findViewById(R.id.camera);
up_arrow = view.findViewById(R.id.up_arrow);
iv_record = view.findViewById(R.id.record);
cameraView.setLifecycleOwner(fragment.getViewLifecycleOwner());
cameraView.mapGesture(Gesture.PINCH, GestureAction.ZOOM); // Pinch to zoom!
toLandAnim= AnimationUtils.loadAnimation(mContext, R.anim.view_to_landscape);
toPortAnim= AnimationUtils.loadAnimation(mContext, R.anim.view_to_portrait);
orientationListener = new MirrorFragment.OrientationListener(mContext);
childFragment = new DiscoveryFragment();
FragmentTransaction transaction = getChildFragmentManager().beginTransaction();
transaction.replace(R.id.frame_video, childFragment);
transaction.addToBackStack(null);
transaction.commit();
}
#Override
public void onResume() {
super.onResume();
cameraView.start();
}
#Override
public void onPause() {
super.onPause();
cameraView.stop();
}
#Override
public void onDestroy() {
super.onDestroy();
cameraView.destroy();
}
#Override
public void onStart() {
orientationListener.enable();
super.onStart();
}
#Override
public void onStop() {
super.onStop();
orientationListener.disable();
}
#Override
public void onMultiWindowModeChanged(boolean isInMultiWindowMode) {
super.onMultiWindowModeChanged(isInMultiWindowMode);
}
private void getHeightWidth() {
/* draggingPanelHeight = mLayout.getHeight();
draggingPanelWidth = mLayout.getWidth();*/
DisplayMetrics displayMetrics = new DisplayMetrics();
getActivity().getWindowManager().getDefaultDisplay().getMetrics(displayMetrics);
height = displayMetrics.heightPixels;
width = displayMetrics.widthPixels;
}
private class OrientationListener extends OrientationEventListener{
final int ROTATION_0 = 1;
final int ROTATION_90 = 2;
final int ROTATION_180 = 3;
final int ROTATION_270 = 4;
private int rotation = 0;
public OrientationListener(Context context) { super(context); }
#Override public void onOrientationChanged(int orientation) {
if( (orientation < 35 || orientation > 325) && rotation!= ROTATION_0){ // PORTRAIT
getHeightWidth();
rotation = ROTATION_0;
frameContainer.startAnimation(toPortAnim);
}
else if( orientation > 145 && orientation < 215 && rotation!=ROTATION_180){ // REVERSE PORTRAIT
getHeightWidth();
rotation = ROTATION_180;
frameContainer.startAnimation(toPortAnim);
}
else if(orientation > 55 && orientation < 125 && rotation!=ROTATION_270){ // REVERSE LANDSCAPE
getHeightWidth();
rotation = ROTATION_270;
//param = new RelativeLayout.LayoutParams((int)width/2,ViewGroup.LayoutParams.MATCH_PARENT);
frameContainer.setLayoutParams(new LinearLayout.LayoutParams((int)height/2,(int)width));
frameContainer.startAnimation(toLandAnim);
}
else if(orientation > 235 && orientation < 305 && rotation!=ROTATION_90){ //LANDSCAPE
getHeightWidth();
rotation = ROTATION_90;
//param = new RelativeLayout.LayoutParams((int)width/2,ViewGroup.LayoutParams.MATCH_PARENT);
frameContainer.setLayoutParams(new LinearLayout.LayoutParams((int)height/2,(int)width));
frameContainer.startAnimation(toLandAnim);
}
}
}
}
My problem is how to change the scrolling behaviour of recyclerView when it rotates to 90 degrees. Please find attached screenshot for reference.
If you see the attached screenshot then you can see when I rotated the frame container it rotated object inside it which is recylerView but in landscape it's scrolling like it scroll in portrait mode.

Change attributes use_flash true/false with button

i made barcode scaner with barcodereader. Flash active on the layout can be used well...
But with button onclick, I do not understand using it ...
is there anything that can help ??
Layout Scanner :
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.material.components.activity.ScanLogin">
<fragment
android:id="#+id/barcode_scanner"
android:name="info.androidhive.barcode.BarcodeReader"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:auto_focus="true"
app:use_flash="false" />
<info.androidhive.barcode.ScannerOverlay
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_alignParentTop="true"
android:layout_marginTop="-100dp"
android:background="#drawable/bg_red"
app:line_color="#color/global_color_green_primary"
app:line_speed="6"
app:line_width="4"
app:square_height="200"
app:square_width="200" />
<ImageButton
android:id="#+id/btnSwitch"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBottom="#+id/barcode_scanner"
android:layout_centerHorizontal="true"
android:layout_marginBottom="20dp"
android:background="#null"
android:contentDescription="#null"
android:src="#drawable/btn_off" />
</RelativeLayout>
Activity Scanner :
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.login_scan);
barcodeReader = (BarcodeReader) getSupportFragmentManager().findFragmentById(R.id.barcode_scanner);
btnSwitch = (ImageButton) findViewById(R.id.btnSwitch);
toggleButtonImage();
btnSwitch.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (isFlashOn) {
ledoff();
} else {
ledon();
}
}
});
}
void ledon() {
isFlashOn = true;
playSound();
toggleButtonImage();
framescan.setTag(Camera.Parameters.FLASH_MODE_ON);
}
void ledoff() {
isFlashOn = false;
playSound();
toggleButtonImage();
framescan.setTag(Camera.Parameters.FLASH_MODE_OFF);
}
toglebutton serves to change the condition of the button to be on/off.
playsound works to play sound ... no problem with toglebutton and playsound. promlem in function use_flash.
private void getCamera() {
if (camera == null) {
try {
camera = Camera.open();
params = camera.getParameters();
} catch (Exception e) {
}
}}
private void turnOffFlash() {
if (isFlashOn) {
if (camera == null || params == null) {
return;
}
// play sound
params = camera.getParameters();
params.setFlashMode(Parameters.FLASH_MODE_OFF);
camera.setParameters(params);
camera.stopPreview();
isFlashOn = false;
// changing button/switch image
toggleButtonImage();
}}
private void turnOnFlash() {
if (!isFlashOn) {
if (camera == null || params == null) {
return;
}
// play sound
playSound();
params = camera.getParameters();
params.setFlashMode(Parameters.FLASH_MODE_TORCH);
camera.setParameters(params);
camera.startPreview();
isFlashOn = true;
// changing button/switch image
toggleButtonImage();
}}
This code will help to achieve your requirements.And not forget to ask for the permission for the camera.

Intersecting two images in different Layouts

How it looks
I want to check intersection between ImageView to ImageView2 as LinearLayout slides towards ImageView2.
I used Rect but it is not working, ImageView2 Just passed throught it without getting intersect.
Please help me!!
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:clickable="true" >
<ImageView
android:id="#+id/tile"
android:layout_width="30dp"
android:layout_height="30dp"
android:src="#drawable/tile" />
<LinearLayout
android:id="#+id/l1"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:weightSum="100" >
<ImageView
android:id="#+id/b1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="50"
android:background="#000"
android:src="#drawable/b" />
<ImageView
android:id="#+id/b2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="70dp"
android:layout_weight="50"
android:background="#000"
android:src="#drawable/b" />
</LinearLayout>
#SuppressLint("NewApi")
public class MainActivity extends Activity {
Rect tileRect = new Rect();
Rect b1Rect = new Rect();
Rect b2Rect = new Rect();
ImageView tile,b1,b2;
RelativeLayout layout;
LinearLayout l1;
final Handler h = new Handler();
Boolean tileRight=false;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
init();
move();
}
private void init() {
// TODO Auto-generated method stub
b1 = (ImageView)findViewById(R.id.b1);
b2 = (ImageView)findViewById(R.id.b2);
tile = (ImageView)findViewById(R.id.tile);
layout = (RelativeLayout)findViewById(R.id.layout);
l1 = (LinearLayout)findViewById(R.id.l1);
tile.setX(320);
tile.setY(800);
l1.setVisibility(View.VISIBLE);
}
public void move()
{
final int delay = 45;
h.postDelayed(new Runnable()
{
#Override
public void run() {
// TODO Auto-generated method stub
layout.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View arg0, MotionEvent event) {
// TODO Auto-generated method stub
if(event.getAction() == MotionEvent.ACTION_UP)
{
if(tileRight==true)
tileRight=false;
else
tileRight=true;
return true;
}
return false;
}
});
if(tileRight==true)
{
if(tile.getX()>600f)
{
tile.setX(tile.getX());
}
else{
tile.setX(tile.getX()+speedTile);
}
}
else{
if(tile.getX()<40f)
{
tile.setX(tile.getX());
}
else{
tile.setX(tile.getX()-speedTile);
}
}
tile.getHitRect(tileRect);
b1.getHitRect(b1Rect);
b2.getHitRect(b2Rect);
if(Rect.intersects(tileRect, b1Rect) || Rect.intersects(tileRect, b2Rect))
{
gameOver();
}
l1.setY(l1.getY()+10f);
h.postDelayed(this, delay);
}
},delay);
}
private void gameOver() {
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
Android's View has getLocationOnScreen() method that shows absolute position of your view.
https://developer.android.com/reference/android/view/View.html#getLocationOnScreen(int[])
The issue occurs because view.getHitRect() is used before the layouts are inflated.
Any of the view's position or measurement APIs like getWidth(), getTop(), getRight() etc. will return 0 (getHitRect() initializes the Rect with (0,0,0,0)) in onCreate() or onResume() before the views are inflated.
In your case, it appears that the Handler's delay period executes the intersection logic earlier than view inflation.
You could post from the view and the run() method will execute after the view inflates and then obtain the view's measurement parameters or a Rect .
Here is an example:
public class MyTestActivity extends AppCompatActivity{
int mNumberOfViewsInitialized = 0;
ImageView mImageViewRight, mImageViewLeft;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.sliding_image_activity);
mImageViewLeft = (ImageView) findViewById(R.id.image_view_left);
mImageViewRight = (ImageView) findViewById(R.id.image_view_right);
// calling method here will log that the views do not intersect
// which happens because they haven't been inflated yet.
// doViewsOverlap();
mImageViewLeft.post(new Runnable(){
#Override
public void run() {
mNumberOfViewsInitialized++;
intersectionLogic();
}
});
mImageViewRight.post(new Runnable(){
#Override
public void run() {
mNumberOfViewsInitialized++;
intersectionLogic();
}
});
}
private void intersectionLogic(){
/* the constant could be something else, depending
on the number of views you'd like to test intersection for*/
if(mNumberOfViewsInitialized == 2){
doViewsOverlap(mImageViewLeft,mImageViewRight);
}
}
private void doViewsOverlap(final View firstView, final View secondView){
Rect leftRect = new Rect();
firstView.getHitRect(leftRect);
Rect rightRect = new Rect();
secondView.getHitRect(rightRect);
if(Rect.intersects(leftRect,rightRect) || Rect.intersects(rightRect,leftRect))
Log.v("intersects","views intersect");
else
Log.v("intersects","views do not intersect");
}
}
I used a layout which does not animate / move the images, but the same issue should occur when the images are moved as well
<ImageView
android:id="#+id/image_view_left"
android:layout_width="300dp"
android:layout_height="300dp"
android:layout_alignParentLeft="true"
android:background="#android:color/holo_blue_dark"
android:src = "#mipmap/ic_launcher"/>
<ImageView
android:id="#+id/image_view_right"
android:layout_width="300dp"
android:layout_height="300dp"
android:layout_alignParentRight="true"
android:background="#android:color/holo_green_dark"
android:gravity="end"
android:src="#mipmap/ic_launcher"/>
Images contained in a RelativeLayout.
Here is a screenshot of the UI:
This problem is related to this: If I call getMeasuredWidth() or getWidth() for layout in onResume they return 0
Hope this helps.

ImageView moving behind Camera Surface View

I am trying to place an imageview over a Camera surfaceview, when the application starts the imageview is on top of the camera preview but after a picture is taken and is set to the imageview the RelativeLayout that the camera preview is nested in moves forward when startpreview is called to start the camera again so the camera preview ends up above the imageview. There are buttons in the same layout placed after the imageview in the xml layout and those are not affected. If I don't start the camera again after a picture the imageview has it's image and is visible. Dumping the view hierarchy verifies the same. As far as I can tell this should be something fairly straight-forward, so I'm not sure where I'm going wrong.
UPDATE: I have also attempted to add a completely new ImageView with the bitmap programmatically after the camera is started and that ImageView is moved behind as well.
XML:
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:id="#+id/add_activity"
android:layout_height="fill_parent"
>
<RelativeLayout
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:id="#+id/camera_preview"
/>
<ImageView
android:layout_width="fill_parent"
android:id="#+id/beforeImageView"
android:src="#drawable/app_icon"
android:alpha="0.2"
android:layout_height="fill_parent" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Back"
android:id="#+id/close_camera"
android:layout_gravity="bottom|left"
android:layout_marginBottom="10dp"
android:layout_marginLeft="10dp"
android:gravity="bottom|left"
android:layout_alignParentBottom="true"
android:layout_alignParentLeft="true" />
<Button
android:id="#+id/button_capture"
android:text="Before"
android:layout_width="wrap_content"
android:layout_height="60dp"
android:layout_gravity="center_horizontal|bottom"
android:layout_marginBottom="20dp"
android:background="#color/purple"
android:textColor="#color/white"
android:paddingLeft="5dp"
android:paddingRight="5dp"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true" />
<ProgressBar
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/add_progress_bar"
android:layout_gravity="center" />
</FrameLayout>
JAVA:
public class AddActivity extends Activity {
private Camera mCamera;
CameraPreview mPreview;
private RelativeLayout preview;
boolean useFrontCamera = true;
boolean tookBeforeImage = false;
boolean tookAfterImage = false;
Bitmap beforeImage;
ProgressBar progressBar;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add);
//Hide Notification and Action Bars
View decorView = getWindow().getDecorView();
int uiOptions = View.SYSTEM_UI_FLAG_FULLSCREEN;
decorView.setSystemUiVisibility(uiOptions);
ActionBar actionBar = getActionBar();
actionBar.hide();
progressBar = (ProgressBar) findViewById(R.id.add_progress_bar);
progressBar.setVisibility(View.INVISIBLE);
boolean cameraCheck = checkCameraHardware(getApplicationContext());
if (cameraCheck) {
StartCamera cameraLaunch = new StartCamera();
cameraLaunch.execute();
}
Button closeCameraButton = (Button) findViewById(R.id.close_camera);
closeCameraButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
releaseCamera();
View decorView = getWindow().getDecorView();
int uiOptions = View.SYSTEM_UI_FLAG_VISIBLE;
decorView.setSystemUiVisibility(uiOptions);
ActionBar actionBar = getActionBar();
actionBar.show();
finish();
}
});
Button captureButton = (Button) findViewById(R.id.button_capture);
captureButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mCamera.takePicture(null,null,mPicture);
}
});
}
private boolean checkCameraHardware(Context context) {
if (context.getPackageManager().hasSystemFeature(PackageManager.FEATURE_CAMERA)) {
return true;
} else {
return false;
}
}
private void releaseCamera() {
if (mCamera != null) {
mCamera.release();
mCamera = null;
}
}
#Override
protected void onPause() {
super.onPause();
releaseCamera();
}
#Override
public void onBackPressed() {
releaseCamera();
super.onBackPressed();
}
#Override
protected void onResume() {
super.onResume();
//Hide Notification and Action Bars
View decorView = getWindow().getDecorView();
int uiOptions = View.SYSTEM_UI_FLAG_FULLSCREEN;
decorView.setSystemUiVisibility(uiOptions);
ActionBar actionBar = getActionBar();
actionBar.hide();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
//getMenuInflater().inflate(R.menu.menu_add, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
//return true;
}
return super.onOptionsItemSelected(item);
}
private class StartCamera extends AsyncTask<String, Void, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
progressBar.setVisibility(View.VISIBLE);
}
#Override
protected String doInBackground(String... params) {
try {
if (useFrontCamera) {
mCamera = Camera.open();
mCamera.enableShutterSound(true);
} else {
//Flip Camera
}
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
mPreview = new CameraPreview(getApplicationContext(),mCamera);
preview = (RelativeLayout) findViewById(R.id.camera_preview);
preview.addView(mPreview,0);
progressBar.setVisibility(View.INVISIBLE);
}
}
private Camera.PictureCallback mPicture = new Camera.PictureCallback() {
#Override
public void onPictureTaken(byte[] data, Camera camera) {
Display display = getWindowManager().getDefaultDisplay();
int rotation = 0;
switch (display.getRotation()) {
case Surface.ROTATION_0: // This is display orientation
rotation = 90;
break;
case Surface.ROTATION_90:
rotation = 0;
break;
case Surface.ROTATION_180:
rotation = 270;
break;
case Surface.ROTATION_270:
rotation = 180;
break;
}
Bitmap bitmap = ImageTools.toBitmap(data);
bitmap = ImageTools.rotate(bitmap, rotation);
if (!tookBeforeImage) {
beforeImage = bitmap;
ResetCamera cameraReset = new ResetCamera();
cameraReset.execute();
Button captureButton = (Button) findViewById(R.id.button_capture);
captureButton.setText("After");
tookBeforeImage = true;
} else if (tookBeforeImage == true && tookAfterImage == false) {
} else {
}
}
};
/** A basic Camera preview class */
public class CameraPreview extends SurfaceView implements SurfaceHolder.Callback {
private SurfaceHolder mHolder;
private Camera mCamera;
public CameraPreview(Context context, Camera camera) {
super(context);
mCamera = camera;
// Install a SurfaceHolder.Callback so we get notified when the
// underlying surface is created and destroyed.
mHolder = getHolder();
this.setBackgroundColor(Color.TRANSPARENT);
mHolder.addCallback(this);
// deprecated setting, but required on Android versions prior to 3.0
mHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
}
public void surfaceCreated(SurfaceHolder holder) {
// The Surface has been created, now tell the camera where to draw the preview.
try {
mCamera.setDisplayOrientation(90);
mCamera.setPreviewDisplay(holder);
mCamera.startPreview();
} catch (IOException e) {
Log.d("Camera Error", "Error setting camera preview: " + e.getMessage());
}
}
public void surfaceDestroyed(SurfaceHolder holder) {
// empty. Take care of releasing the Camera preview in your activity.
}
public void surfaceChanged(SurfaceHolder holder, int format, int w, int h) {
// If your preview can change or rotate, take care of those events here.
// Make sure to stop the preview before resizing or reformatting it.
if (mHolder.getSurface() == null){
// preview surface does not exist
return;
}
// stop preview before making changes
try {
mCamera.stopPreview();
} catch (Exception e){
// ignore: tried to stop a non-existent preview
}
// set preview size and make any resize, rotate or
// reformatting changes here
// start preview with new settings
try {
mCamera.setPreviewDisplay(mHolder);
mCamera.startPreview();
} catch (Exception e){
Log.d("Camera Error", "Error starting camera preview: " + e.getMessage());
}
}
}
private static class ImageTools {
public static Bitmap toBitmap(byte[] data) {
return BitmapFactory.decodeByteArray(data, 0, data.length);
}
public static Bitmap rotate(Bitmap in, int angle) {
Matrix mat = new Matrix();
mat.postRotate(angle);
return Bitmap.createBitmap(in, 0, 0, in.getWidth(), in.getHeight(), mat, true);
}
}
private class ResetCamera extends AsyncTask<String, Void, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
progressBar.setVisibility(View.VISIBLE);
}
#Override
protected String doInBackground(String... params) {
mCamera.startPreview();
return null;
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
ImageView beforeImageView = (ImageView) findViewById(R.id.beforeImageView);
beforeImageView.setImageBitmap(beforeImage);
beforeImageView.setImageAlpha(100);
//Trying to add programmatically still ends up behind Camera Preview
ImageView newBefore = (ImageView) new ImageView(getApplicationContext());
newBefore.setImageBitmap(beforeImage);
newBefore.setLayoutParams(new ViewGroup.LayoutParams(
ViewGroup.LayoutParams.MATCH_PARENT,
ViewGroup.LayoutParams.WRAP_CONTENT));
preview.addView(newBefore,0);
progressBar.setVisibility(View.INVISIBLE);
}
}
}
It was due to trying to load too large of a bitmap, it was quietly throwing a notice in the log as it was unable to create a texture. Reducing the bitmap's size solved the issue.

Mediacontroller behind navigation bar

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
android:paddingBottom="#dimen/activity_vertical_margin"
tools:context="tk.ejb1123.quickflix.VideoPayer"
android:background="#android:color/black"
android:id="#+id/layoutf">
<VideoView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/videoView"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_centerVertical="true"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true" />
<ProgressBar
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/progressBar"
android:layout_centerVertical="true"
android:layout_centerHorizontal="true"
android:visibility="visible" />
#Override
public void onWindowFocusChanged(boolean hasFocus) {
super.onWindowFocusChanged(hasFocus);
if (hasFocus) {
View decorView;
decorView = findViewById(R.id.videoView);
decorView.setSystemUiVisibility(
View.SYSTEM_UI_FLAG_LAYOUT_STABLE
| View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
| View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
| View.SYSTEM_UI_FLAG_HIDE_NAVIGATION
| View.SYSTEM_UI_FLAG_FULLSCREEN
// | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY
);}
}
link to the images example: http://imgur.com/Zq6Cq7M
I tried changing the gravity and it does not seem to work, and I could not find anything on the internet to fix this issue. The mediaContoller is anchored to R.id.videoView. I don't know how this works in other apps like play books.
I faced the same issue recently, I didn't find any good way to solve it, but that workaround :
First get the navigation_bar_height :
int resourceId = resources.getIdentifier("navigation_bar_height", "dimen", "android");
if (resourceId > 0) {
mNavigationBarSize = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, getResources().getDimension(resourceId), resources.getDisplayMetrics());
}
Then, you can add a listener to your mediaController, something like that (mRelativeLayout is the parent of my videoview) :
mMediaController.addOnAttachStateChangeListener(new View.OnAttachStateChangeListener() {
#Override
public void onViewAttachedToWindow(View view) {
((FrameLayout.LayoutParams) mRelativeLayout.getLayoutParams()).bottomMargin = mNavigationBarSize;
mRelativeLayout.requestLayout();
}
#Override
public void onViewDetachedFromWindow(View view) {
hideSystemUI();
((FrameLayout.LayoutParams) mRelativeLayout.getLayoutParams()).bottomMargin = 0;
mRelativeLayout.requestLayout();
}
});
I hope it will help you
Edit : if your activity have a "white theme", you'll see a little graphical glitch when switching, you may have to add : <item name="android:windowBackground">#null</item> in the theme of this activity (or do it programmaticly)
I got the solution by setting Gravity and Margins.
Layout File
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#android:color/black">
<VideoView
android:id="#+id/videoSurface"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_gravity="center"/>
<ProgressBar
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/my_spinner"
android:layout_gravity="center"/>
</FrameLayout>
Now, on OnCreate() set MediaController layout and assign the same using setLayoutParams().
#Override
protected 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.activity_sample_video);
ColorDrawable drawable = new ColorDrawable(Color.argb(100,0,0,0));
getSupportActionBar().setBackgroundDrawable(drawable);
getSupportActionBar().setTitle("Big Bunny");
spinner = (ProgressBar)findViewById(R.id.my_spinner);
dm = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(dm);
lpp = new FrameLayout.LayoutParams(dm.widthPixels, 170);
lpp.gravity= Gravity.BOTTOM;
lpp.setMargins(0,0,0,100);
video = (VideoView)findViewById(R.id.videoSurface);
video.setVideoPath("http://clips.vorwaerts-gmbh.de/big_buck_bunny.mp4");
video.setMediaController(mediaController = new MediaController(this){
#Override
public boolean dispatchKeyEvent(KeyEvent event) {
if (event.getKeyCode() == KeyEvent.KEYCODE_BACK ) {
if (event.getAction() == KeyEvent.ACTION_DOWN) {
return true;
} else if (event.getAction() == KeyEvent.ACTION_UP) {
((Activity) getContext()).onBackPressed();
return true;
}
}
return super.dispatchKeyEvent(event);
}
});
hideSystemUI();
mediaController.setLayoutParams(lpp);
mediaController.setAlpha(0.5f);
video.start();
video.setOnCompletionListener(this);
video.setOnInfoListener(this);
}
If you want, you can also handle orientation changes using below code.
#Override
public void onConfigurationChanged(Configuration newConfig)
{
super.onConfigurationChanged(newConfig);
// Checks the orientation of the screen
if (newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE)
{
getWindowManager().getDefaultDisplay().getMetrics(dm);
lpp = new FrameLayout.LayoutParams(dm.widthPixels, 170);
//lpp.gravity= Gravity.BOTTOM;
//lpp.setMargins(0,0,0,100);
mediaController.setLayoutParams(lpp);
//Toast.makeText(getApplicationContext(),"Landscape",Toast.LENGTH_LONG).show();
}
else if (newConfig.orientation == Configuration.ORIENTATION_PORTRAIT)
{
getWindowManager().getDefaultDisplay().getMetrics(dm);
lpp = new FrameLayout.LayoutParams(dm.widthPixels, 170);
lpp.gravity= Gravity.BOTTOM;
lpp.setMargins(0,0,0,100);
mediaController.setLayoutParams(lpp);
//Toast.makeText(getApplicationContext(),"Portrait",Toast.LENGTH_LONG).show();
}
}

Categories

Resources