Device Rotation with wrong camera overlay dimension - java

I am fairly new to coding and app development(almost a month) so please bear with me. I am working on an app that uses a Barcode scanning plugin (customized as per needs).
In the app's main view (first window) I have a block, which on click triggers the Barcode plugin's scan(). This opens a scanner of the exact dimensions as the block of the main view. But if I rotate the device, the Barcode scanner view's dimensions goes haywire.
Is there a way I can adjust/change the x,y,w,h values of the Barcode scanner view so to align it with my app's block in the main view?
Upon clicking the Scan block on my app's main view, this scanner is opened as an overlay with custom buttons:
Upon rotating the device and clicking the scan block (green block on app's main view), this is how it looks:
Angular code passing the dimensions for the green scan block on app's main view:
.directive('barcodeScanner', function ($localStorage, _, $window) {
function link(scope, element, attrs){
scope.scanning = false;
scope.paused = false;
//Barcode-Scanning Green Window
var width = $window.innerWidth;
var height = width * 3/4;
if(width > 450){
width = 400;
height = 300;
}
scope.dimensionStyle = {
width: width+"px",
height: height+"px",
"margin-left" : "auto",
"margin-right" : "auto"
}
scope.$on('stop-scanner', function () {
scope.paused=false;
stopScanner();
});
scope.$on('start-scanner', function () {
scope.paused=true;
startScanner();
});
var mH = $window.innerHeight,
mW = $window.innerWidth;
var startBtn = element[0].querySelector('.barcode-start-btn');
function startScanner(){
var rect = startBtn.getBoundingClientRect();
var options = {
wPer : rect.width/mW,
hPer : rect.height/mH,
yPer : rect.top/mH,
xPer : rect.left/mW
}
scope.scanning = true;
cordova.plugins.barcodescanner.scan(function(result) {
scope.$emit('barcode-scanned',result);
},
options
);
}
My barcodescanner.java of the plugin that is triggered to open the scanner:
#Override
public boolean execute(String action, JSONArray args, CallbackContext callbackContext) {
this.callbackContext = callbackContext;
this.requestArgs = args;
if (action.equals(SCAN)) {
// create fragment
if(!hasPermisssion()) {
requestPermissions(0);
} else {
scan(args);
}
} else if(action.equals(STOP)) {
stop(args);
} else {
return false;
}
return true;
}
public void scan(final JSONArray args) {
final CordovaPlugin that = this;
cordova.getThreadPool().execute(new Runnable() {
public void run() {
int maxHeight = webView.getView().getHeight();
int maxWidth = webView.getView().getWidth();
double xPer = 0/360;
double yPer = 82/568;
double hPer = 270/568;
double wPer = 360/360;
// add config as intent extras
if (args.length() > 0) {
JSONObject obj;
for (int i = 0; i < args.length(); i++) {
try {
obj = args.getJSONObject(i);
if(obj.has(X_PER)){
xPer = obj.getDouble(X_PER);
}
if(obj.has(Y_PER)){
yPer = obj.getDouble(Y_PER);
}
if(obj.has(H_PER)){
hPer = obj.getDouble(H_PER);
}
if(obj.has(W_PER)){
wPer = obj.getDouble(W_PER);
}
} catch (JSONException e) {
Log.i("CordovaLog", e.getLocalizedMessage());
continue;
}
}
}
Bundle bundle = new Bundle();
bundle.putDouble("x", maxWidth*xPer);
bundle.putDouble("y", maxHeight*yPer);
bundle.putDouble("w", maxWidth*wPer);
bundle.putDouble("h", maxHeight*hPer);
openCameraPopup(bundle);
}
});
}
My fragment class that implements ZxingScannerView:
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle state) {
if(state == null){
state = this.getArguments();
}
if(state != null) {
x = state.getDouble("x");
y = state.getDouble("y");
w = state.getDouble("w");
h = state.getDouble("h");
}
mScannerView = new ZXingScannerView(getActivity()){
#Override
public void setupCameraPreview(CameraWrapper cameraWrapper) {
super.setupCameraPreview(cameraWrapper);
buttonStop = new Button(getActivity());
buttonStop.setText("STOP");
ViewGroup.LayoutParams params = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
this.addView(buttonStop);
buttonStop.setOnClickListener( new OnClickListener() {
#Override
public void onClick(View v) {
mScannerView.stopCamera();
mScannerView.removeAllViews();
}
});
}
};
mScannerView.setZ(10);
mScannerView.setAutoFocus(true);
mScannerView.setFlash(false);
mScannerView.setX((float) x);
mScannerView.setY((float) y);
mScannerView.setLayoutParams(new ViewGroup.LayoutParams((int)w, (int)h));
return mScannerView;
}

I suggest you to lock your position using screen orientation landscape. So it will change position everytime you rotate your mobile.

Related

How to add image depending on what result or emotion it might detect

I have been trying to figure this out all day, as I would like to add an image depending on the outcome of the emotion may detect. Just wanted to add some some images but I'm still new to this. Can anyone help me with this one to.
btw here's my code:
public class DetectionActivity extends AppCompatActivity {
// Background task of face detection.
private class DetectionTask extends AsyncTask<InputStream, String, Face[]> {
private boolean mSucceed = true;
#Override
protected Face[] doInBackground(InputStream... params) {
// Get an instance of face service client to detect faces in image.
FaceServiceClient faceServiceClient = SampleApp.getFaceServiceClient();
try {
publishProgress("Detecting...");
// Start detection.
return faceServiceClient.detect(
params[0], /* Input stream of image to detect */
true, /* Whether to return face ID */
true, /* Whether to return face landmarks */
new FaceServiceClient.FaceAttributeType[]{
FaceServiceClient.FaceAttributeType.Emotion,
});
} catch (Exception e) {
mSucceed = false;
publishProgress(e.getMessage());
addLog(e.getMessage());
return null;
}
}
#Override
protected void onPreExecute() {
mProgressDialog.show();
addLog("Request: Detecting in image " + mImageUri);
}
#Override
protected void onProgressUpdate(String... progress) {
mProgressDialog.setMessage(progress[0]);
setInfo(progress[0]);
}
#Override
protected void onPostExecute(Face[] result) {
if (mSucceed) {
addLog("Response: Success. Detected " + (result == null ? 0 : result.length)
+ " face(s) in " + mImageUri);
}
// Show the result on screen when detection is done.
setUiAfterDetection(result, mSucceed);
}
}
// Flag to indicate which task is to be performed.
private static final int REQUEST_SELECT_IMAGE = 0;
// The URI of the image selected to detect.
private Uri mImageUri;
// The image selected to detect.
private Bitmap mBitmap;
// Progress dialog popped up when communicating with server.
ProgressDialog mProgressDialog;
// When the activity is created, set all the member variables to initial state.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_detection);
//this hides the back button and I thank you
getSupportActionBar().setDisplayHomeAsUpEnabled(false);
mProgressDialog = new ProgressDialog(this);
mProgressDialog.setTitle(getString(R.string.progress_dialog_title));
// Disable button "detect" as the image to detect is not selected.
setDetectButtonEnabledStatus(false);
LogHelper.clearDetectionLog();
}
// Save the activity state when it's going to stop.
#Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putParcelable("ImageUri", mImageUri);
}
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater menuInflater = getMenuInflater();
menuInflater.inflate(R.menu.menu, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch(item.getItemId()){
case R.id.menuAbout:
// Toast.makeText(this, "You clicked about", Toast.LENGTH_SHORT).show();
View messageView = getLayoutInflater().inflate(R.layout.about, null, false);
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setIcon(R.drawable.smile);
builder.setTitle(R.string.app_name);
builder.setView(messageView);
builder.create();
builder.show();
break;
case R.id.menuHelp:
// Toast.makeText(this, "You clicked settings", Toast.LENGTH_SHORT).show();
// Intent help = new Intent(this, HelpActivity.class);
//startActivity(help);
// break;
View messageViewh = getLayoutInflater().inflate(R.layout.help, null, false);
AlertDialog.Builder builderh = new AlertDialog.Builder(this);
builderh.setIcon(R.drawable.smile);
builderh.setTitle(R.string.app_nameh);
builderh.setView(messageViewh);
builderh.create();
builderh.show();
break;
}
return true;
}
// Recover the saved state when the activity is recreated.
#Override
protected void onRestoreInstanceState(#NonNull Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
mImageUri = savedInstanceState.getParcelable("ImageUri");
if (mImageUri != null) {
mBitmap = ImageHelper.loadSizeLimitedBitmapFromUri(
mImageUri, getContentResolver());
}
}
// Called when image selection is done.
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
switch (requestCode) {
case REQUEST_SELECT_IMAGE:
if (resultCode == RESULT_OK) {
// If image is selected successfully, set the image URI and bitmap.
mImageUri = data.getData();
mBitmap = ImageHelper.loadSizeLimitedBitmapFromUri(
mImageUri, getContentResolver());
if (mBitmap != null) {
// Show the image on screen.
ImageView imageView = (ImageView) findViewById(R.id.image);
imageView.setImageBitmap(mBitmap);
// Add detection log.
addLog("Image: " + mImageUri + " resized to " + mBitmap.getWidth()
+ "x" + mBitmap.getHeight());
}
// Clear the detection result.
FaceListAdapter faceListAdapter = new FaceListAdapter(null);
ListView listView = (ListView) findViewById(R.id.list_detected_faces);
listView.setAdapter(faceListAdapter);
// Clear the information panel.
setInfo("");
// Enable button "detect" as the image is selected and not detected.
setDetectButtonEnabledStatus(true);
}
break;
default:
break;
}
}
// Called when the "Select Image" button is clicked.
public void selectImage(View view) {
Intent intent = new Intent(this, SelectImageActivity.class);
startActivityForResult(intent, REQUEST_SELECT_IMAGE);
}
// Called when the "Detect" button is clicked.
public void detect(View view) {
// Put the image into an input stream for detection.
ByteArrayOutputStream output = new ByteArrayOutputStream();
mBitmap.compress(Bitmap.CompressFormat.JPEG, 100, output);
ByteArrayInputStream inputStream = new ByteArrayInputStream(output.toByteArray());
// Start a background task to detect faces in the image.
new DetectionTask().execute(inputStream);
// Prevent button click during detecting.
setAllButtonsEnabledStatus(false);
}
// View the log of service calls.
public void viewLog(View view) {
Intent intent = new Intent(this, DetectionLogActivity.class);
startActivity(intent);
}
// Show the result on screen when detection is done.
private void setUiAfterDetection(Face[] result, boolean succeed) {
// Detection is done, hide the progress dialog.
mProgressDialog.dismiss();
// Enable all the buttons.
setAllButtonsEnabledStatus(true);
// Disable button "detect" as the image has already been detected.
setDetectButtonEnabledStatus(false);
if (succeed) {
// The information about the detection result.
String detectionResult;
if (result != null) {
detectionResult = result.length + " face"
+ (result.length != 1 ? "s" : "") + " detected";
// Show the detected faces on original image.
ImageView imageView = (ImageView) findViewById(R.id.image);
imageView.setImageBitmap(ImageHelper.drawFaceRectanglesOnBitmap(
mBitmap, result, true));
// Set the adapter of the ListView which contains the details of the detected faces.
FaceListAdapter faceListAdapter = new FaceListAdapter(result);
// Show the detailed list of detected faces.
ListView listView = (ListView) findViewById(R.id.list_detected_faces);
listView.setAdapter(faceListAdapter);
} else {
detectionResult = "0 face detected";
}
setInfo(detectionResult);
}
mImageUri = null;
mBitmap = null;
}
// Set whether the buttons are enabled.
private void setDetectButtonEnabledStatus(boolean isEnabled) {
Button detectButton = (Button) findViewById(R.id.detect);
detectButton.setEnabled(isEnabled);
}
// Set whether the buttons are enabled.
private void setAllButtonsEnabledStatus(boolean isEnabled) {
Button selectImageButton = (Button) findViewById(R.id.select_image);
selectImageButton.setEnabled(isEnabled);
Button detectButton = (Button) findViewById(R.id.detect);
detectButton.setEnabled(isEnabled);
// Button ViewLogButton = (Button) findViewById(R.id.view_log);
// ViewLogButton.setEnabled(isEnabled);
}
// Set the information panel on screen.
private void setInfo(String info) {
TextView textView = (TextView) findViewById(R.id.info);
textView.setText(info);
}
// Add a log item.
private void addLog(String log) {
LogHelper.addDetectionLog(log);
}
// The adapter of the GridView which contains the details of the detected faces.
private class FaceListAdapter extends BaseAdapter {
// The detected faces.
List<Face> faces;
// The thumbnails of detected faces.
List<Bitmap> faceThumbnails;
// Initialize with detection result.
FaceListAdapter(Face[] detectionResult) {
faces = new ArrayList<>();
faceThumbnails = new ArrayList<>();
if (detectionResult != null) {
faces = Arrays.asList(detectionResult);
for (Face face : faces) {
try {
// Crop face thumbnail with five main landmarks drawn from original image.
faceThumbnails.add(ImageHelper.generateFaceThumbnail(
mBitmap, face.faceRectangle));
} catch (IOException e) {
// Show the exception when generating face thumbnail fails.
setInfo(e.getMessage());
}
}
}
}
#Override
public boolean isEnabled(int position) {
return false;
}
#Override
public int getCount() {
return faces.size();
}
#Override
public Object getItem(int position) {
return faces.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
if (convertView == null) {
LayoutInflater layoutInflater =
(LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = layoutInflater.inflate(R.layout.item_face_with_description, parent, false);
}
convertView.setId(position);
// Show the face thumbnail.
((ImageView) convertView.findViewById(R.id.face_thumbnail)).setImageBitmap(
faceThumbnails.get(position));
// Show the face details.
String getEmotion;
// String improve = improveMessage(getEmotion);
DecimalFormat formatter = new DecimalFormat("#0.0");
//add
// String message = findMessage(getEmotion());
// String improve = improveMessage(getEmotion);
String face_description = String.format("Emotion: %s\n",
getEmotion(faces.get(position).faceAttributes.emotion)
);
((TextView) convertView.findViewById(R.id.text_detected_face)).setText(face_description);
return convertView;
}
private String getEmotion(Emotion emotion) {
String emotionType = "";
double emotionValue = 0.0;
String emotionInfo = "";
if (emotion.anger > emotionValue) {
emotionValue = emotion.anger;
emotionType = "Anger";
emotionInfo = "If you haven't fed him/her yet maybe this precious one is thirsty or hungry.\n Try giving your attention. If your baby is acting unusual it's best to seek for medical help.";
}
if (emotion.contempt > emotionValue) {
emotionValue = emotion.contempt;
emotionType = "Contempt";
emotionInfo = "You go girl!";
}
if (emotion.disgust > emotionValue) {
emotionValue = emotion.disgust;
emotionType = "Disgust";
emotionInfo = "Look! If your baby is feeling this way mabye she/he doesn't like this. \n If what your doing right now is good for him/her maybe you can support that.";
}
if (emotion.fear > emotionValue) {
emotionValue = emotion.fear;
emotionType = "Fear";
emotionInfo = "Your baby looks somewhat uncomfortable.\n Make your baby feel comfortable and take note of what makes them feel like that. ";
}
if (emotion.happiness > emotionValue) {
emotionValue = emotion.happiness;
emotionType = "Happiness";
emotionInfo = "Just continue what you are doing. It is important to remember what can make them happy. \n";
}
if (emotion.neutral > emotionValue) {
emotionValue = emotion.neutral;
emotionType = "Neutral";
emotionInfo = "Maybe you should just observe first";
}
if (emotion.sadness > emotionValue) {
emotionValue = emotion.sadness;
emotionType = "Sadness";
emotionInfo = "Just cuddle or dandle your baby.";
}
if (emotion.surprise > emotionValue) {
emotionValue = emotion.surprise;
emotionType = "Surprise";
emotionInfo = "Oooh look. Play with your baby. Try doing peek a boo";
}
return String.format("%s: %f \n\n%s", emotionType, emotionValue, emotionInfo);
}
}
}
Just would like to add some images like happy if that is the detected emotion. Please do help me. Any help is highly appreciated. Thank you :)
I would like to add that after the emotionInfo.
I guess detectWithStream is you want.
Official Doc: Faces.detectWithStream Method
From Java SDK, the List<DetectedFace> object will return if successful.

How do I implement drag and drop in my game?

I have been looking all over SOF and online tutorials, but for some reason I still can't get it to work. I want to implement a drag and drop functionality in my game. Here is the activity:
I want to be able to drag and drop the 4 shapes in the bottom. If the correct shape fits, I want the shape with the "?" to change into the correct shape. Can someone show me how I can do this?
Here is my code:
public class SecondActivity extends AppCompatActivity {
int n;
ImageView shape1, shape2, shape3, shape4, guessShape;
ImageButton exit;
private android.widget.RelativeLayout.LayoutParams layoutParams;
Random rand = new Random();
ImageView[] shapes = new ImageView[4];
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_second);
//declare each imageview
shape1 = (ImageView) findViewById(R.id.shape1);
shape2 = (ImageView) findViewById(R.id.shape2);
shape3 = (ImageView) findViewById(R.id.shape3);
shape4 = (ImageView) findViewById(R.id.shape4);
guessShape = (ImageView) findViewById(R.id.guessShape);
exit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
finish();
System.exit(0);
}
});
//add each imageView to the shapes[] array
shapes[0] = shape1;
shapes[1] = shape2;
shapes[2] = shape3;
shapes[3] = shape4;
//store all the shapes in an array
int[] images = new int[]{R.drawable.img_0, R.drawable.img_1, R.drawable.img_2, R.drawable.img_3, R.drawable.img_4,
R.drawable.img_5, R.drawable.img_6, R.drawable.img_7, R.drawable.img_8, R.drawable.img_9, R.drawable.img_10,
R.drawable.img_11, R.drawable.img_12, R.drawable.img_13, R.drawable.img_14, R.drawable.img_15, R.drawable.img_16,
R.drawable.img_17};
//store all the guessShapes in an array
int[] outlines = new int[]{R.drawable.outline_0, R.drawable.outline_1, R.drawable.outline_2,
R.drawable.outline_3, R.drawable.outline_4, R.drawable.outline_5, R.drawable.outline_6,
R.drawable.outline_7, R.drawable.outline_8, R.drawable.outline_9, R.drawable.outline_10,
R.drawable.outline_11, R.drawable.outline_12, R.drawable.outline_13, R.drawable.outline_14,
R.drawable.outline_15, R.drawable.outline_16, R.drawable.outline_17};
//generate 4 random images from the array's and ensure that they don't match each other
ArrayList<Integer> list = new ArrayList<Integer>();
for (int i = 0; i < 18; i++) {
list.add(new Integer(i));
}
Collections.shuffle(list);
int whichImg = (int) Math.round((Math.random() * 4));
int img1 = list.get(0);
int img2 = list.get(1);
int img3 = list.get(2);
int img4 = list.get(3);
if (whichImg == 1) {
whichImg = img1;
} else if (whichImg == 2) {
whichImg = img2;
} else if (whichImg == 3) {
whichImg = img3;
} else {
whichImg = img4;
}
int outlineID = outlines[whichImg];
//set the shape in each imageview
guessShape.setBackgroundResource(outlineID);
shape1.setBackgroundResource(images[img1]);
shape2.setBackgroundResource(images[img2]);
shape3.setBackgroundResource(images[img3]);
shape4.setBackgroundResource(images[img4]);
//ensures that 1/4 shape has the guess shape correspondence
final Object currentBackground = guessShape.getBackground().getConstantState();
//for loop to have the guess shape and 1/4 shapes to match
for (int i = 0; i < 18; i++) {
if (currentBackground.equals(getResourceID("outline_" + i, "drawable", getApplicationContext()))) {
int random = new Random().nextInt(shapes.length);
shapes[random].setBackgroundResource(getResourceID("img_" + i, "drawable", getApplicationContext()));
}
//set tags for each view
guessShape.setTag("gShape");
shape1.setTag("S_1");
shape2.setTag("S_2");
shape3.setTag("S_3");
shape4.setTag("S_4");
}
}
//method to get the ID of an image in drawable folder
protected final static int getResourceID(final String resName, final String resType, final Context ctx)
{
final int ResourceID =
ctx.getResources().getIdentifier(resName, resType,
ctx.getApplicationInfo().packageName);
if (ResourceID == 0)
{
throw new IllegalArgumentException
(
"No resource string found with name " + resName
);
}
else
{
return ResourceID;
}
}
}
Although you were not clear enough.
Try this, First make a class that implements onTouchListener
private final class MyTouchListener implements OnTouchListener {
public boolean onTouch(View view, MotionEvent motionEvent) {
if (motionEvent.getAction() == MotionEvent.ACTION_DOWN) {
ClipData data = ClipData.newPlainText("", "");
DragShadowBuilder shadowBuilder = new View.DragShadowBuilder(
view);
view.startDrag(data, shadowBuilder, view, 0);
view.setVisibility(View.INVISIBLE);
return true;
} else {
return false;
}
}
}
Then define a drag listener
class MyDragListener implements OnDragListener {
Drawable enterShape = getResources().getDrawable(
R.drawable.shape_droptarget);
Drawable normalShape = getResources().getDrawable(R.drawable.shape);
#Override
public boolean onDrag(View v, DragEvent event) {
int action = event.getAction();
switch (event.getAction()) {
case DragEvent.ACTION_DRAG_STARTED:
// do nothing
break;
case DragEvent.ACTION_DRAG_ENTERED:
v.setBackgroundDrawable(enterShape);
break;
case DragEvent.ACTION_DRAG_EXITED:
v.setBackgroundDrawable(normalShape);
break;
case DragEvent.ACTION_DROP:
// Dropped, reassign View to ViewGroup
View view = (View) event.getLocalState();
ViewGroup owner = (ViewGroup) view.getParent();
owner.removeView(view);
LinearLayout container = (LinearLayout) v;
container.addView(view);
view.setVisibility(View.VISIBLE);
break;
case DragEvent.ACTION_DRAG_ENDED:
v.setBackgroundDrawable(normalShape);
default:
break;
}
return true;
}
}
Now simply use these lines
findViewById(R.id.myimage1).setOnTouchListener(new MyTouchListener());
and
findViewById(R.id.bottomleft).setOnDragListener(new MyDragListener());
Here are some tutorials that might help you
Tutorialpoint
Link 2

putting a pause in code to show image after image?

I am a complete beginner in android. I am stuck at a point in making an application. I have images stored in hashmap and whatever line I give it as an input is broken into separate words on basis of space and its corresponding images are fetched. But I dont want these images to show up at once but these should be shown one after the other and there should be a pause of almost one second between each image to show up. But seems like I am stuck because of my inexperience. In code where and how should I place a pause? Because when I use Thread.sleep anywhere in code, it pause only in beginning everytime.
textlist.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,int position, long id) {
Speech.setText("You said " + matches_text.get(position));
selectedFromList = (matches_text.get(position));
String[] separated = selectedFromList.split(" ");
// ImageView iv;
final int[] imageViews = { R.id.imageView1,
R.id.imageView2, R.id.imageView3, R.id.imageView4,
R.id.imageView5, R.id.imageView6, R.id.imageView7,
R.id.imageView8, R.id.imageView9, R.id.imageView10,
R.id.imageView11, R.id.imageView12,
R.id.imageView13, R.id.imageView14,
R.id.imageView15, R.id.imageView16,
};
final_length = separated.length;
int b = 0;
HashMap<String, Integer> map = new HashMap<String, Integer>();
map.put("apple",R.drawable.apple);
maps pol=new maps();
pol.map_A();
pol.map_B();
pol.map_C();
pol.map_D();
pol.map_E();
for (int i = 0; i < separated.length; i++) {
iv = (ImageView) findViewById(imageViews[i]);
LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(
100, 100);
iv.setLayoutParams(layoutParams);
if(pol.map_a.containsKey(separated[i].toLowerCase())){
iv.setImageResource(pol.map_a.get(separated[i].toLowerCase()));
}
else if(pol.map_b.containsKey(separated[i].toLowerCase())){
iv.setImageResource(pol.map_b.get(separated[i].toLowerCase()));
}
else if(pol.map_c.containsKey(separated[i].toLowerCase())){
iv.setImageResource(pol.map_c.get(separated[i].toLowerCase()));
}
else if(pol.map_d.containsKey(separated[i].toLowerCase())){
iv.setImageResource(pol.map_d.get(separated[i].toLowerCase()));
}
else if(pol.map_e.containsKey(separated[i].toLowerCase())){
iv.setImageResource(pol.map_e.get(separated[i].toLowerCase()));
}
}}
Change your for loop as following:
Handler handler1 = new Handler();
for (int i = 0; i < separated.length; i++) {
final int iDupe = i;
handler1.postDelayed(new Runnable() {
public void run() {
iv = (ImageView) findViewById(imageViews[iDupe]);
LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(100, 100);
iv.setLayoutParams(layoutParams);
if(pol.map_a.containsKey(separated[iDupe].toLowerCase())) {
iv.setImageResource(pol.map_a.get(separated[iDupe].toLowerCase()));
}
else if(pol.map_b.containsKey(separated[iDupe].toLowerCase())) {
iv.setImageResource(pol.map_b.get(separated[iDupe].toLowerCase()));
}
else if(pol.map_c.containsKey(separated[iDupe].toLowerCase())) {
iv.setImageResource(pol.map_c.get(separated[iDupe].toLowerCase()));
}
else if(pol.map_d.containsKey(separated[iDupe].toLowerCase())) {
iv.setImageResource(pol.map_d.get(separated[iDupe].toLowerCase()));
}
else if(pol.map_e.containsKey(separated[iDupe].toLowerCase())) {
iv.setImageResource(pol.map_e.get(separated[iDupe].toLowerCase()));
}
}
}, i * 1000);
}

Android java | Suttering and lags when updating View layout params

Recently I'm making a game which requires continuous animation.
I'll explain it further.
I got view let's say top of the screen and I need to animate it from the top of the screen to the bottom of the screen and then it will go back to the original spot (Top of the screen) when the view is on the bottom.
Now there's 6 views which does the exactly same thing.
Animate from top of the screen to the bottom of the screen and back when they are on the bottom.
But when they are already moving there's really annoying stuttering and lags on the application.
Here's the code :
#Override
public void onWindowFocusChanged(boolean focus) {
new LongOperation().execute();
}
private class LongOperation extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... params) {
play.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if (!failedM) {
running = true;
soundPool.play(click_sound, 1, 1, 0, 0, 1);
play.setVisibility(View.INVISIBLE);
p1.setVisibility(View.VISIBLE);
p2.setVisibility(View.VISIBLE);
p3.setVisibility(View.VISIBLE);
c1.setVisibility(View.VISIBLE);
c2.setVisibility(View.VISIBLE);
c3.setVisibility(View.VISIBLE);
final Handler mHandler = new Handler();
new Thread(new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
while (true) {
try {
Thread.sleep(60);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
mHandler.post(new Runnable() {
#Override
public void run() {
p1.getHitRect(rect1);
p2.getHitRect(rect2);
p3.getHitRect(rect3);
c1.getHitRect(rect4);
c2.getHitRect(rect5);
c3.getHitRect(rect6);
if (Rect.intersects(rect, rect1)
{
.....
}
if (Rect.intersects(rect, rect2)
) {
.....
}
if (Rect.intersects(rect, rect3)
) {
.....
}
if (Rect.intersects(rect, rect4)
) {
.....
}
if (Rect.intersects(rect, rect5)
) {
.....
}
if (Rect.intersects(rect, rect6)
) {
.....
}
downy1 += 1;
downy2 += 1;
downy3 += 1;
downy4 += 1;
downy5 += 1;
downy6 += 1;
params1.topMargin = params1.topMargin
+ downy1;
params2.topMargin = params2.topMargin
+ downy2;
params3.topMargin = params3.topMargin
+ downy3;
params4.topMargin = params4.topMargin
+ downy4;
params5.topMargin = params5.topMargin
+ downy5;
params6.topMargin = params6.topMargin
+ downy6;
p1.setLayoutParams(params1);
p2.setLayoutParams(params2);
p3.setLayoutParams(params3);
c1.setLayoutParams(params4);
c2.setLayoutParams(params5);
c3.setLayoutParams(params6);
if (p1.getTop() > height) {
downy1 = 0;
params1.leftMargin = newX;
params1.topMargin = orig1y;
p1.setLayoutParams(params1);
}
if (p2.getTop() > height) {
downy2 = 0;
params2.leftMargin = newX;
params2.topMargin = orig2y;
p2.setLayoutParams(params2);
}
if (p3.getTop() > height) {
downy3 = 0;
params3.leftMargin = newX;
params3.topMargin = orig3y;
p3.setLayoutParams(params3);
}
if (c1.getTop() > height
&& !failedM) {
downy4 = 0;
params4.leftMargin = newX;
params4.topMargin = orig4y;
c1.setLayoutParams(params4);
}
if (c2.getTop() > height
&& !failedM) {
downy5 = 0;
params5.leftMargin = newX;
params5.topMargin = orig5y;
c2.setLayoutParams(params5);
}
if (c3.getTop() > height
&& !failedM) {
downy6 = 0;
params6.leftMargin = newX;
params6.topMargin = orig6y;
c3.setLayoutParams(params6);
}
}
});
}
}
}).start();
}
});
return "Executed";
}
#Override
protected void onPostExecute(String result) {
}
#Override
protected void onPreExecute() {
}
#Override
protected void onProgressUpdate(Void... values) {
}
}
As you can see there's (if view.getTop() > height)
What it means is that when the view Y is bigger than the height which is when the view is moving from the top to the bottom it will go back to the top.
I hope I made it clear
Thanks in advance.
You should use the animation framework. (view.animate()...).
Setting layout params requires re-calculating the layout, which is potentially not a cheap operation (depends on your layout).
You can use animation framework or set translateX/Y etc properties of the view, which avoid re-calculating the layout.

How to swipe zoomed image using ImageViews and PageAdapter

I am trying to create an image viewer which can load images from given URLs.The code below implement the User Interface.
My intention is to let user Zoom the image and move to next image with a Swipe event.But the problem is that when i zoom and then swipe , instead of showing the remaining portion , it moves to the next image.
I tried using requestDisallowInterceptTouchEvent in TouchImageView's(https://github.com/MikeOrtiz/TouchImageView) onTouchListener .After this the remaining portion could show but now i cannot go to the next page. I was wondering how this can be achieved as the event can only go to either TouchView or PageAdapter
public class PageActivity extends Activity {
private int numPages = 33;
private TouchImageView[] imageViews = new TouchImageView[numPages];
private String URL = "http://www.smbc-comics.com/comics/200905";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
ViewPager viewPager = new ViewPager(this);
for (int i = 0; i < numPages; i++) {
imageViews[i] = new TouchImageView(this);
imageViews[i].setBackgroundResource(R.drawable.banke);
imageViews[i].setMaxZoom(4f);
}
setContentView(viewPager);
ImagePagerAdapter adapter = new ImagePagerAdapter();
viewPager.setAdapter(adapter);
viewPager.setOffscreenPageLimit(2);
}
#SuppressWarnings("unused")
private class ImagePagerAdapter extends PagerAdapter {
#Override
public int getCount() {
return numPages;
}
#Override
public boolean isViewFromObject(View view, Object object) {
return view == ((TouchImageView) object);
}
#Override
public Object instantiateItem(ViewGroup container, int position) {
Context context = PageActivity.this;
String pageURL = URL;
if (imageViews[position].getDrawable() == null) {
ImageFetcher imagefetcher = new ImageFetcher();
imagefetcher.execute(
pageURL + String.format("%02d", position+1) + ".gif",
String.valueOf(position));
}
((ViewPager) container).addView(imageViews[position], 0);
return imageViews[position];
}
#Override
public void destroyItem(ViewGroup container, int position, Object object) {
((ViewPager) container).removeView((TouchImageView) object);
imageViews[position].setImageDrawable(null);
}
}
public class ImageFetcher extends AsyncTask<String, Integer, Drawable> {
int fillthisPos;
public Drawable doInBackground(String... urls) {
try {
InputStream is = (InputStream) new URL(urls[0]).getContent();
fillthisPos = Integer.parseInt(urls[1]);
Drawable d = Drawable.createFromStream(is, "src name");
return d;
} catch (Exception e) {
return null;
}
}
#Override
protected void onPostExecute(Drawable result) {
super.onPostExecute(result);
imageViews[fillthisPos].setImageDrawable(result);
result = null;
}
}
}
You can add following code in TouchImageView class:
public boolean isZoomed () {
return (normalizedScale > minScale);
}
private void onSwipeEvent(MotionEvent event) {
boolean zoomed = this.isZoomed();
if (!zoomed && (swipeLen > 0)) {
if (event.getAction() == MotionEvent.ACTION_DOWN) {
swipeStartPos = (int) event.getRawX();
}
else if (event.getAction() == MotionEvent.ACTION_MOVE) {
int distance = ((int) event.getRawX()) - swipeStartPos;
int swipeVector = SWIPE_RIGHT;
if (distance < 0) swipeVector = SWIPE_LEFT;
if (Math.abs(distance) > swipeLen) {
onSwipeHandler.onSwipe(swipeVector);
swipeStartPos = (int) event.getRawX();
this.setScaleX(1f);
}
else {
int swipeStDist = swipeLen - Math.round(((swipeLen / 100) * 50));
if (Math.abs(distance) > swipeStDist) {
this.setScaleX(0.98f);
}
}
}
else if (event.getAction() == MotionEvent.ACTION_UP) {
swipeStartPos = (int) event.getRawX();
this.setScaleX(1f);
}
}
}
public static int SWIPE_LEFT = 0;
public static int SWIPE_RIGHT = 1;
public int swipeStartPos = 0;
public onSwipeListener onSwipeHandler = new onSwipeListener() {
public void onSwipe(int vector) {}
};
public static int swipeLen = 0;
public void setOnSwipeListener(onSwipeListener c, int swipeLength) {
onSwipeHandler = c;
swipeLen = swipeLength;
}
public interface onSwipeListener {
public void onSwipe(int vector);
}
And also in TouchImageView below line 636 add onSwipeEvent(event) like this:
......
setImageMatrix(matrix);
onSwipeEvent(event);
//
// indicate event was handled
//
return true;
...........
After this from you code you can add swipe event listener, like this:
imageView.setOnSwipeListener(new TouchImageView.onSwipeListener() {
#Override
public void onSwipe(int vector) {
if (vector == TouchImageView.SWIPE_LEFT) {
Log.d("swipe", "swipe left!");
}
else if (vector == TouchImageView.SWIPE_RIGHT) {
Log.d("swipe", "swipe right!");
}
}
}, 200); //length of swiping - 200 dip
This onSwipeListener ignore onswipe where image is zoomed+. It work for me.

Categories