How to change the layout when we touch wrong item? - java

I need to run this app as follow -> : if I touch correct item , score+=5, else change to gameover.xml
I don't know how to change activity to another layout?
public boolean onTouchEvent(MotionEvent event) {
int tx = (int) event.getX();
int ty = (int) event.getY();
int i = 0;
for (Element element : mElements) {
if ((element.getmX() < tx && tx < element.getmX()
+ element.getWidth())
&& (element.getmY() < ty && ty < element.getmY()
+ element.getHeight())) {
***if (mGarbagType == element.getGtype()) {
score += 5;
}else score-=5;***
Log.v("DustmanGame", "Touch on:" + element.getGtype()
+ "Score : 5");
mElements.remove(i);
mElementNumber = mElements.size();
mGarbagType = randomGarbage();
break;
}
i++;
}
return super.onTouchEvent(event);
}

I don't know how to change activity to another layout
In your else {} block simply launch a new Activity with startActivity() to use gameover.xml or call setContentView(R.layout.gameover) in this Activity.

Have different layout in your xml, use View.GONE or View.VISIBLE depends on your requirement

Related

Android 2 finger touch triggering 1 finger touch as well as 2 finger touch

I have an issue in my app where I need to perform a different action based on if one fingers or two fingers are pressed down.
Currently I have the follow code:
#Override
public boolean onTouchEvent(MotionEvent event){
int touchX = (int)event.getX();
int touchY = (int)event.getY();
int action = event.getActionMasked();
//Multitouch
if(event.getPointerCount() > 1 && action == MotionEvent.ACTION_POINTER_DOWN){
System.out.println("2 Finger press");
return true;
}
else if(action == MotionEvent.ACTION_DOWN && action != MotionEvent.ACTION_POINTER_DOWN){
if(event.getPointerCount() == 1) {
System.out.println("single finger down");
invalidate();
return true;
}
}
return false;
}
The issue I am having is when I press with 2 fingers, the multitouch part registers, and after that so does the single press.
I did some googling around on ways to fix that and that would be why I am checking on the single touch conditional that action != MotionEvent.ACTION_POINTER_DOWN which I thought would fix the issue. That didn't fix the issue hence I decided to check that event.getPointerCount() == 1, but unfortunately that still causes both lines to print when I press with 2 fingers.
To summarize I need to only call the 2 finger part when 2 fingers are pressed down and not both.
refer to the documentation on "Handling Multi-Touch Gestures". it details exactly what you're looking for.
in essence, each active pointer is assigned an ID when it makes contact with the screen. your solution will should take into account which IDs come into play and are removed by observing various action states.
something a little bit along these lines (but beware compatibility calls for methods like getActionIndex()):
UPDATED CODE SAMPLE
public class MotionActivity extends AppCompatActivity {
private int primaryPointerId = -1;
private int secondaryPointerId = -1;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(new FrameLayout(this));
}
#Override
public boolean onTouchEvent(MotionEvent event){
int action = event.getActionMasked();
switch(action) {
case MotionEvent.ACTION_DOWN:
primaryPointerId = event.getPointerId(0);
Log.d(getClass().getName(), "Primary pointer ID == [" + primaryPointerId + "]");
break;
case MotionEvent.ACTION_POINTER_DOWN:
secondaryPointerId = event.getPointerId(event.getActionIndex());
Log.d(getClass().getName(), "Secondary pointer ID == [" + secondaryPointerId + "]");
break;
case MotionEvent.ACTION_MOVE:
if(primaryPointerId > -1 && secondaryPointerId > -1) {
Log.d(getClass().getName(), "Two-point touch...");
} else {
Log.d(getClass().getName(), "One-point touch...");
}
break;
case MotionEvent.ACTION_POINTER_UP:
if(event.getPointerId(event.getActionIndex()) == primaryPointerId) {
primaryPointerId = secondaryPointerId;
}
secondaryPointerId = -1;
break;
case MotionEvent.ACTION_UP:
primaryPointerId = -1;
break;
}
return true;
}
}

Making a responsive control in JavaFX

I'm trying to make a responsive design like in Word. I used Toolbar and ToolbarSkin code and made changes to it. Now I don't know how to make it so it will check the priority of the control, and the lowest priority gets resized, while the control with the highest priority still shows full-size.
Code I changed in ToolbarSkin:
private void addNodesToToolBar() {
final Responser toolbar = getSkinnable();
double length = 0;
if (getSkinnable().getOrientation() == Orientation.VERTICAL) {
length = snapSize(toolbar.getHeight()) - snappedTopInset() - snappedBottomInset() + getSpacing();
} else {
length = snapSize(toolbar.getWidth()) - snappedLeftInset() - snappedRightInset() + getSpacing();
}
// Is there overflow ?
double x = 0;
boolean hasOverflow = false;
for (Node node : getSkinnable().getItems()) {
if (getSkinnable().getOrientation() == Orientation.VERTICAL) {
x += snapSize(node.prefHeight(-1)) + getSpacing();
} else {
x += snapSize(node.prefWidth(-1)) + getSpacing();
}
if (x > length) {
hasOverflow = true;
break;
}
}
if (hasOverflow) {
if (getSkinnable().getOrientation() == Orientation.VERTICAL) {
length -= snapSize(overflowMenu.prefHeight(-1));
} else {
length -= snapSize(overflowMenu.prefWidth(-1));
}
length -= getSpacing();
}
// Determine which node goes to the toolbar and which goes to the overflow.
x = 0;
overflowMenuItems.clear();
box.getChildren().clear();
for (Node node : getSkinnable().getItems()) {
node.getStyleClass().remove("menu-item");
node.getStyleClass().remove("custom-menu-item");
if (getSkinnable().getOrientation() == Orientation.VERTICAL) {
x += snapSize(node.prefHeight(-1)) + getSpacing();
} else {
x += snapSize(node.prefWidth(-1)) + getSpacing();
}
if (x <= length) {
box.getChildren().add(node);
} else {
if (node.isFocused()) {
if (!box.getChildren().isEmpty()) {
Node last = engine.selectLast();
if (last != null) {
last.requestFocus();
}
} else {
overflowMenu.requestFocus();
}
}
if (node instanceof Separator) {
overflowMenuItems.add(new SeparatorMenuItem());
} else {
CustomMenuItem customMenuItem = new CustomMenuItem(node);
// RT-36455:
// We can't be totally certain of all nodes, but for the
// most common nodes we can check to see whether we should
// hide the menu when the node is clicked on. The common
// case is for TextField or Slider.
// This list won't be exhaustive (there is no point really
// considering the ListView case), but it should try to
// include most common control types that find themselves
// placed in menus.
final String nodeType = node.getTypeSelector();
switch (nodeType) {
case "Button":
case "Hyperlink":
case "Label":
customMenuItem.setHideOnClick(true);
break;
case "CheckBox":
case "ChoiceBox":
case "ColorPicker":
case "ComboBox":
case "DatePicker":
case "MenuButton":
case "PasswordField":
case "RadioButton":
case "ScrollBar":
case "ScrollPane":
case "Slider":
case "SplitMenuButton":
case "SplitPane":
case "TextArea":
case "TextField":
case "ToggleButton":
case "ToolBar":
customMenuItem.setHideOnClick(false);
break;
}
overflowMenuItems.add(customMenuItem);
box.getChildren().clear();
setNameToButton(make,box.getParent().getId());
box.getChildren().add(make);
// overflowMenuItems.remove(overflowMenuItems.size()-1);
}
}
}
// Check if we overflowed.
overflow = overflowMenuItems.size() > 0;
if (!overflow && overflowMenu.isFocused()) {
Node last = engine.selectLast();
if (last != null) {
last.requestFocus();
}
}
overflowMenu.setVisible(overflow);
overflowMenu.setManaged(overflow);
}
and:
#Override protected void layoutChildren(final double x,final double y,
final double w, final double h) {
final Responser toolbar = getSkinnable();
if (toolbar.getOrientation() == Orientation.VERTICAL) {
if (snapSize(toolbar.getHeight()) != previousHeight || needsUpdate) {
((VBox)box).setSpacing(getSpacing());
((VBox)box).setAlignment(getBoxAlignment());
previousHeight = snapSize(toolbar.getHeight());
addNodesToToolBar();
}
} else {
if (snapSize(toolbar.getWidth()) != previousWidth || needsUpdate) {
((HBox)box).setSpacing(getSpacing());
((HBox)box).setAlignment(getBoxAlignment());
previousWidth = snapSize(toolbar.getWidth());
addNodesToToolBar();
}
}
needsUpdate = false;
double toolbarWidth = w;
double toolbarHeight = h;
if (getSkinnable().getOrientation() == Orientation.VERTICAL) {
toolbarHeight -= (overflow ? snapSize(overflowMenu.prefHeight(-1)) : 0);
} else {
toolbarWidth -= (overflow ? snapSize(overflowMenu.prefWidth(-1)) : 0);
}
box.resize(toolbarWidth, toolbarHeight);
positionInArea(box, x, y,
toolbarWidth, toolbarHeight, /*baseline ignored*/0, HPos.CENTER, VPos.CENTER);
// If popup menu is not null show the overflowControl
if (overflow) {
double overflowMenuWidth = snapSize(overflowMenu.prefWidth(-1));
double overflowMenuHeight = snapSize(overflowMenu.prefHeight(-1));
double overflowX = x;
double overflowY = x;
if (getSkinnable().getOrientation() == Orientation.VERTICAL) {
// This is to prevent the overflow menu from moving when there
// are no items in the toolbar.
if (toolbarWidth == 0) {
toolbarWidth = savedPrefWidth;
}
HPos pos = ((VBox)box).getAlignment().getHpos();
if (HPos.LEFT.equals(pos)) {
overflowX = x + Math.abs((toolbarWidth - overflowMenuWidth)/2);
} else if (HPos.RIGHT.equals(pos)) {
overflowX = (snapSize(toolbar.getWidth()) - snappedRightInset() - toolbarWidth) +
Math.abs((toolbarWidth - overflowMenuWidth)/2);
} else {
overflowX = x +
Math.abs((snapSize(toolbar.getWidth()) - (x) +
snappedRightInset() - overflowMenuWidth)/2);
}
overflowY = snapSize(toolbar.getHeight()) - overflowMenuHeight - y;
} else {
// This is to prevent the overflow menu from moving when there
// are no items in the toolbar.
if (toolbarHeight == 0) {
toolbarHeight = savedPrefHeight;
}
VPos pos = ((HBox)box).getAlignment().getVpos();
if (VPos.TOP.equals(pos)) {
overflowY = y +
Math.abs((toolbarHeight - overflowMenuHeight)/2);
} else if (VPos.BOTTOM.equals(pos)) {
overflowY = (snapSize(toolbar.getHeight()) - snappedBottomInset() - toolbarHeight) +
Math.abs((toolbarHeight - overflowMenuHeight)/2);
} else {
overflowY = y + Math.abs((toolbarHeight - overflowMenuHeight)/2);
}
overflowX = snapSize(toolbar.getWidth()) - overflowMenuWidth - snappedRightInset();
}
overflowMenu.resize(overflowMenuWidth, overflowMenuHeight);
positionInArea(overflowMenu, overflowX, overflowY, overflowMenuWidth, overflowMenuHeight, /*baseline ignored*/0,
HPos.CENTER, VPos.CENTER);
}
}
Also I don't know how can I implement so only one control will shrink at the time, not all of them.
Thank you for your help.

How To Get Position's Value from ArrayList

I m displaying Image and name From ArrayList>
on View I want to get Position value From The view
profileimage.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
use=arraylist.get(i).get("User_Id");
new userbyid().execute();
}
});
i m getting Like this In Array List But Its Always giving Same id On image Click
I want to get Value Of view position
here is setimage fuction Where i m displaying image and name
public void settheimage(int j)
{
for (i = j; i < j+10; i++)
{
LayoutInflater inflate = (LayoutInflater)getActivity()
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
final View m_view = inflate.inflate(R.layout.custom_layout, null);
ImageView m_image = (ImageView) m_view.findViewById(R.id.sp_image);
LinearLayout m_topLayout = (LinearLayout) m_view.findViewById(R.id.sp_color);
tempusername=(TextView)m_view.findViewById(R.id.username);
ImageView profileimage=(ImageView)m_view.findViewById(R.id.profileimage);
LinearLayout m_bottomLayout = (LinearLayout) m_view.findViewById(R.id.sp_linh);
//final RelativeLayout myRelView = new RelativeLayout(this);
m_view.setLayoutParams(new LayoutParams((windowwidth - 80), 450));
m_view.setX(40);
m_view.setY(40);
m_view.setTag(i);
Image=arraylist.get(i).get("User_Image");
tempuser_id=arraylist.get(i).get("User_Id");
username=arraylist.get(i).get("FirstName");
tempusername.setText(username);
Picasso.with(getActivity()).load(Image).into(m_image);
// m_image.setBackgroundResource(myImageList[i]);
if (i == 0) {
m_view.setRotation(-1);
} else if (i == 1) {
m_view.setRotation(-5);
} else if (i == 2) {
m_view.setRotation(3);
} else if (i == 3) {
m_view.setRotation(7);
} else if (i == 4) {
m_view.setRotation(-2);
} else if (i == 5) {
m_view.setRotation(5);
}
// ADD dynamically like button on image.
final Button imageLike = new Button(getActivity());
imageLike.setLayoutParams(new LayoutParams(100, 50));
imageLike.setBackgroundDrawable(getResources().getDrawable(R.drawable.like));
imageLike.setX(20);
imageLike.setY(-250);
imageLike.setAlpha(alphaValue);
m_topLayout.addView(imageLike);
// ADD dynamically dislike button on image.
final Button imagePass = new Button(getActivity());
imagePass.setLayoutParams(new LayoutParams(100, 50));
imagePass.setBackgroundDrawable(getResources().getDrawable(R.drawable.dislike));
imagePass.setX(260);
imagePass.setY(-300);
imagePass.setAlpha(alphaValue);
m_topLayout.addView(imagePass);
profileimage.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
use=arraylist.get(i).get("User_Id");
new userbyid().execute();
}
});
m_topLayout.setOnTouchListener(new OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
x_cord = (int) event.getRawX();
y_cord = (int) event.getRawY();
/* m_view.setX(x_cord - screenCenter + 40);
m_view.setY(y_cord - 150);*/
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
x = (int) event.getX();
y = (int) event.getY();
Log.v("On touch", x + " " + y);
break;
case MotionEvent.ACTION_MOVE:
x_cord = (int) event.getRawX(); // Updated for more
// smoother animation.
y_cord = (int) event.getRawY();
m_view.setX(x_cord - x);
m_view.setY(y_cord - y);
// m_view.setY(y_cord-y);
// y_cord = (int) event.getRawY();
// m_view.setX(x_cord - screenCenter + 40);
// m_view.setY(y_cord - 150);
if (x_cord >= screenCenter) {
m_view.setRotation((float) ((x_cord - screenCenter) * (Math.PI / 32)));
if (x_cord > (screenCenter + (screenCenter / 2))) {
imageLike.setAlpha(1);
if (x_cord > (windowwidth - (screenCenter / 4))) {
Likes = 2;
} else {
Likes = 0;
}
} else {
Likes = 0;
imageLike.setAlpha(0);
}
imagePass.setAlpha(0);
} else {
// rotate
m_view.setRotation((float) ((x_cord - screenCenter) * (Math.PI / 32)));
if (x_cord < (screenCenter / 2)) {
imagePass.setAlpha(1);
if (x_cord < screenCenter / 4) {
Likes = 1;
} else {
Likes = 0;
}
} else {
Likes = 0;
imagePass.setAlpha(0);
}
imageLike.setAlpha(0);
}
break;
case MotionEvent.ACTION_UP:
x_cord = (int) event.getRawX();
y_cord = (int) event.getRawY();
Log.e("X Point", "" + x_cord + " , Y " + y_cord);
imagePass.setAlpha(0);
imageLike.setAlpha(0);
if (Likes == 0) {
// Log.e("Event Status", "Nothing");
m_view.setX(40);
m_view.setY(40);
m_view.setRotation(0);
} else if (Likes == 1) {
//Toast.makeText(getActivity(), "dislike the image",Toast.LENGTH_SHORT).show();
listvalue_pos--;
if(listvalue_pos==-1)
{
i=i+10;
listvalue_pos=9;
settheimage(i);
parentView.removeView(m_view);
}
else {
parentView.removeView(m_view);
}
// new deletUSer().execute();
} else if (Likes == 2) {
//Toast.makeText(getActivity(), "like the image",Toast.LENGTH_SHORT).show();
listvalue_pos--;
if(listvalue_pos==-1)
{
i=i+10;
listvalue_pos=9;
settheimage(i);
parentView.removeView(m_view);
}
else {
parentView.removeView(m_view);
}
// new adduser().execute();
}
break;
default:
break;
}
return true;
}
});
parentView.addView(m_view);
}
}
here I m Add hashmap into arraylist
map.put("User_Id", USer_id);
map.put("FirstName",FirstName);
map.put("User_Image", USer_Image);
// Set the JSON Objects into the array
/* list.add(USer_Image);
useridlist.add(USer_id);
usernamelist.add(FirstName);*/
arraylist.add(map);
please give me the answer how to get arralist index value
You can use int index = arraylist.indexOf(yourObject);
I'm not sure that correctly understood what you wanna do
can you show screenshot?
you can set tag for your imageview

dynamic edittext when is destroyed android

I'm writing spreadsheet app for android and for getting cell value i use dynamic edittext.
Is this any way to get info when text is written and save it to cell value?
here is part of code:
#Override
public boolean onTouchEvent(MotionEvent event){
if(Selection != null) {
Cell prevSelection = hostActivity.logic.getCell(Selection.left, Selection.top);
SelTxt = hostActivity.txtInput.getText().toString();
if(SelTxt.length() != 0 && prevSelection.GetValue() != SelTxt && prevSelection.getChanged()) {
prevSelection.setValue(SelTxt);
hostActivity.txtInput.clearComposingText();
prevSelection.Modified(false);
SelTxt = "";
}
}
switch(event.getActionMasked()) {
case MotionEvent.ACTION_DOWN:
int x = (int) event.getX();
int y = (int) event.getY();
calculateSelectionRect(x, y);
SelectionChanged = true;
if(x > startTableX && y > startTableY && !GroupSelected) {
Cell tmpCell = hostActivity.logic.getCell(Selection.left, Selection.top);
hostActivity.EditSelectedCellValue(Selection.left, Selection.top, Selection.right, Selection.bottom, tmpCell);
}
invalidate();
and
if(txtInput != null)
frameLayout.removeView(txtInput);
String tmpText = "";
txtInput = new EditText(this.getApplicationContext());
FrameLayout.LayoutParams txtParams = new FrameLayout.LayoutParams((right - left), (bottom - top));
txtInput.setX(left);
txtInput.setY(top);
txtInput.setText(value.GetValue());
txtInput.setTextColor(R.color.Selected_Cell_Border);
txtInput.setBackgroundColor(getResources().getColor(R.color.Selected_Cell));
frameLayout.addView(txtInput, txtParams);
setContentView(frameLayout);
tmpText = txtInput.getText().toString();
if(txtInput.getText().toString() != value.GetValue())
value.Modified(true);
txtInput.clearComposingText();
return tmpText;
}
in app it works in a way that after filling one cell and selecting cell directly below value is copied once, another selecting this cell gives good empty cell and is ok. But it's annoying and shouldn't happen

Running loop to check integer, not working

I'm trying to get the location of the user's finger touch and detect if it is within the bounds of an image view. I'm getting all the right integers returned to me, there is no problem with the values. The problem I'm getting is when trying to detect whether returnX is greater or less than the imageview X int.
ImageView img;
float eventX;
float eventY;
float x,y,x2,y2;
String TAG = "imgPos";
String TAG2 = "downcheck";
String TAG3 = "bounds";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
img = (ImageView)findViewById(R.id.imageView1);
}
public void fingerDownLoop(){
if (SingleTouchEventView.userDown == true){
Log.e(TAG2, "Down is true");
Thread myThread = new Thread(myRunnable);
myThread.start();
} else if (SingleTouchEventView.userDown == false){
Log.e(TAG2, "Down is false");
}
}
public void getFingerLocation(){
float returnX = SingleTouchEventView.eventX;
float returnY = SingleTouchEventView.eventY;
Log.e(TAG3, " - X -");
Log.e(TAG3, " getX: " + returnX);
Log.e(TAG3, " - Y -");
Log.e(TAG3, " getY: " + returnY);
if (returnX < x){
Log.e(TAG3, "Outside bounds");
}
if (returnX > x){
Log.e(TAG3, "Inside bounds");
}
}
Runnable myRunnable = new Runnable() {
#Override
public void run() {
while (SingleTouchEventView.userDown == true) {
try {
Log.e(TAG2, "FingerDown");
getFingerLocation();
x = img.getLeft();
Thread.sleep(500);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} // Waits for 1 second (1000 milliseconds)
}
}
};
}
testText is a button click, it gets the imageviews position and stores it as the values. The problem I'm getting is here:
if (returnX < x){
Log.e(TAG3, "Outside bounds");
}
if (returnX > x){
Log.e(TAG3, "Inside bounds");
}
It is all ways showing as Inside bounds even though returnX is less than X. Any ideas?
Updated get img position.
int[] img_coordinates = new int[2];
img.getLocationOnScreen(img_coordinates);
double x_center = (double)img_coordinates[0] + img.getWidth()/2.0;
double y_center = (double)img_coordinates[1] + img.getHeight()/2.0;
int halfwidth = 150 / 2;
int halfheight = 150 / 2;
yboundtop = y_center - halfheight;
yboundbottom = y_center + halfheight;
xboundleft = x_center - halfwidth;
xboundright = x_center + halfwidth;
float returnX = eventX;
float returnY = eventY;
if (returnX < xboundleft || returnX > xboundright || returnY < yboundtop || returnY > yboundbottom) {
Log.e(TAG3, "Outside bounds");
}
if (returnX > xboundleft && returnX < xboundright && returnY > yboundtop && returnY < yboundbottom) {
Log.e(TAG3, "Inside bounds");
}
I'am not sure what you want to accomplish by your code, but checking in a loop is not very efficient and in this case probably not necessary.
Your imageView has a method getHitRect() and you could use it like this:
Rect hitRect = new Rect();
imageView.getHitRect(hitRect);
if(hitRect.contains(touchEvent.getX(), touchEvent.getY())){
// your touch is inside, do something useful
}
Use it inside your touch-method
Now that I kind of know what you are looking for I think I may be able to help. Override the onTouchEvent() method of your Activity to capture your touch events. This will be much more efficient than doing the loop yourself.
private boolean mTouchInImage = false;
public boolean onTouchEvent(MotionEvent event) {
boolean handledTouch = false;
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
Rect hitRect = new Rect((int)img.getX(), (int)img.getY(),
(int)(mg.getX() + img.getWidth()), (int)(img.getY() + img.getHeight()));
handledTouch = mTouchInImage = hitRect.contains((int)event.getX(), (int)event.getY());
break;
case MotionEvent.ACTION_UP:
case MotionEvent.ACTION_CANCEL:
handledTouch = mTouchInImage;
mTouchInImage = false;
break;
case MotionEvent.ACTION_MOVE:
if (mTouchInImage) {
img.setX(event.getX() - img.getWidth() / 2);
img.setY(event.getY() - img.getHeight() / 2);
img.invalidate();
handledTouch = true;
}
break;
}
return handledTouch;
}

Categories

Resources