moving views positions refresh - android

First of all sorry for my English. I just began development with android
My problem is:
I create an ImageView in a random position, every time you touch the image, it change its position. When you touch you have a probability (%) that appears another Image in another random position. But my problem is when the second image appear, the first one come back to its "created position" and not keeping position.
The "Bomb" is created well, but then the first image back to created position and not the position it is in the moment.
Thanks all for the help
Example of my test code:
public void start(View view) {
width= 60;
height= 60;
layout = (RelativeLayout) findViewById(R.id.rellayout);
widthLayout = layout.getWidth();
heightLayout = layout.getHeight();
r = new Random();
x = r.nextInt(widthLayout - 60);
y = r.nextInt(heightLayout - 60);
imagen = new ImageView(this);
imagen.setImageResource(R.drawable.led_circle_green);
RelativeLayout.LayoutParams paramss = new RelativeLayout.LayoutParams(
60, 60);
paramss.leftMargin = x;
paramss.topMargin = y;
imagen.setAdjustViewBounds(true);
layout.addView(imagen, paramss);
Animation aparecer = AnimationUtils
.loadAnimation(this, R.anim.aparecer);
imagen.startAnimation(aparecer);
imagen.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
// your code here
push();
}
});
public void push() {
createBomb();
move();
}
public void createBomb() {
r = new Random();
int proba = r.nextInt(100);
if (proba < 50) {
x = r.nextInt(widthLayout - 60);
y = r.nextInt(heightLayout - 60);
bomb = new ImageView(this);
bomb.setImageResource(R.drawable.bomb);
RelativeLayout.LayoutParams paramss = new RelativeLayout.LayoutParams(
60, 60);
paramss.leftMargin = x;
paramss.topMargin = y;
bomb.setAdjustViewBounds(true);
layout.addView(bomb, paramss);
}
}
public void move() {
r = new Random();
int proba = r.nextInt(100);
if (proba < 10) {
ximg = r.nextInt(widthLayout - width);
yimg = r.nextInt(heightLayout - height);
imagen.layout(ximg, yimg, ximg + width, yimg + height);
}
}

layout method does not applies persistent changes to a view state. Set new layout params to image view, which will specify it's new position (do not use layout method).
When you add new ImageView2 RelativeLayout decides to relayout its childs and resets ImageView1 position.
Read this.

Related

Scale view to parent layout size

I am trying to scale a view to layout size by using object animator. The view is a LinearLayout. The view does stretch, but not till the screen size in both the directions (i.e X and Y).
Here is the code.
I feel that either the problem is with this:
The formula to calculate how much zoom must be done.
zoomTillX = screen_width/zoomView_width;
zoomTillY = screen_height/zoomView_height;
Or with the Animation property code that is done in a wrong way.
Please let me know how can I achieve a zoom in.
public class MainActivity extends AppCompatActivity {
TextView tv;
double screen_height;
LinearLayout zoomView;
double screen_width;
double zoomTillX;
double zoomTillY;
double zoomView_width;
double zoomView_height;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tv = (TextView) findViewById(R.id.tv);
zoomView = (LinearLayout) findViewById(R.id.zoomView);
DisplayMetrics dm = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(dm);
screen_height = (double)dm.heightPixels;
screen_width = (double)dm.widthPixels;
zoomView.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
#Override
public void onGlobalLayout() {
zoomView.getViewTreeObserver().removeOnGlobalLayoutListener(this);
zoomView_width = (double)zoomView.getMeasuredWidth();
zoomView_height = (double)zoomView.getMeasuredHeight();
}
});
zoomView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
final Handler handler = new Handler(Looper.getMainLooper());
handler.postDelayed(new Runnable() {
#Override
public void run() {
if(zoomView_width > 0 && zoomView_height > 0)
{
zoomTillX = screen_width/zoomView_width;
zoomTillY = screen_height/zoomView_height;
Log.d("VIEW GET X IS ",String.valueOf(zoomView.getX()));
Log.d("VIEW GET Y IS ",String.valueOf(zoomView.getY()));
ObjectAnimator scaleDownX = ObjectAnimator.ofFloat(zoomView, "scaleX", (float)(zoomTillX));
ObjectAnimator scaleDownY = ObjectAnimator.ofFloat(zoomView, "scaleY",(float)(zoomTillY));
List<Animator> oaList = new ArrayList<Animator>();
oaList.add(scaleDownX);
oaList.add(scaleDownY);
AnimatorSet ani = new AnimatorSet();
ani.playTogether(oaList);
ani.setDuration(500);
ani.start();
}else{
handler.postDelayed(this,300);
}
}
},500);
}
});
}
}
This is how it looks finally.
That can be done via ValueAnimator.
Having this layout as the content of activity:
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/content_frame"
android:layout_width="match_parent"
android:layout_height="match_parent">
<View
android:id="#+id/view"
android:layout_width="170dp"
android:layout_height="170dp"
android:background="#3143ff"/>
</FrameLayout>
And in activity's onCreate():
final View view = findViewById(R.id.view);
final View contentView = findViewById(R.id.content_frame);
contentView.setOnClickListener(v -> {
final int screenWidth = contentView.getWidth();
final int screenHeight = contentView.getHeight();
ValueAnimator widthAnimator = ValueAnimator.ofInt(view.getWidth(), screenWidth);
ValueAnimator heightAnimator = ValueAnimator.ofInt(view.getHeight(), screenHeight);
widthAnimator.setDuration(1500);
heightAnimator.setDuration(1500);
widthAnimator.addUpdateListener(animation -> {
view.getLayoutParams().width = (int) animation.getAnimatedValue();
view.requestLayout();
});
heightAnimator.addUpdateListener(animation -> {
view.getLayoutParams().height = (int) animation.getAnimatedValue();
view.requestLayout();
});
widthAnimator.start();
heightAnimator.start();
});
This will be the result:
Transitions API
We've implemented this animation ourselves. But why won't we let the system take care of building all this animators?
There's a Transitions API, which will take the heavy lifting for us. All we have to do, is to ask the framework to detect layout changes, create appropriate animators and run the animations.
So, all the code above can be changed to following, which will result in exactly same output:
contentView.setOnClickListener(v -> {
final int screenWidth = contentView.getWidth();
final int screenHeight = contentView.getHeight();
// Uncomment this, if you want Transitions API to run default animation
// TransitionManager.beginDelayedTransition(contentView);
Transition autoTransition = new AutoTransition();
autoTransition.setDuration(1500);
// With this overload you can control actual transition animation
TransitionManager.beginDelayedTransition(contentView, autoTransition);
// After `beginDelayedTransition()` function perform changes to the layout
// Transitions framework will detect those changes and perform appropriate animations
view.getLayoutParams().width = screenWidth;
view.getLayoutParams().height = screenHeight;
view.requestLayout();
view.invalidate();
});

Translate Animation Android

I have a RecyclerView with Images inside. I need to move clicked image to the center of the screen. And there should be no depend on the images's start point, it should move to the center of the screen.
I've tried to do this using XML code - it does't work correct, TranslateAnimation object - it doesn't work correct. In both variants image's movement depends on the images's start position and final points of all images are different.
I don't know how to do this. Please help me)
Try the following code. The code uses Listview, but the same logic can be applied for RecyclerView.
The approach here is to create a new imageview in the parent layout of the listview overlapping the image that was clicked. Then translate the newly created imageview to the center of the screen.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
root = (RelativeLayout) findViewById(R.id.main_root);
listView = (ListView) findViewById(R.id.list);
MyAdapter adapter = new MyAdapter(MainActivity.this, web, imageId);
listView.setAdapter(adapter);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
ImageView imgView = (ImageView) view.findViewById(R.id.grid_image);
// Get location of window with respect to window.
int location[] = new int[2];
imgView.getLocationInWindow(location);
// Create a new image view overlapping
// the image view that was clicked.
ImageView imgView2 = new ImageView(MainActivity.this);
imgView2.setImageDrawable(imgView.getDrawable());
// To make it overlap, use the location values of
// the clicked image as left and top margin for the
// new image.
RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(
imgView.getWidth(), imgView.getHeight());
params.leftMargin = location[0];
params.topMargin = location[1] - getStatusBarHeight();
// Add the new image view to the root view of the activity.
root.addView(imgView2, params);
translateToCenter(imgView2, location);
}
});
}
/**
* To translate the new image view to the center of the screen.
* #param view
* #param originalLoc
*/
private void translateToCenter(View view , int originalLoc[])
{
int xMove = root.getWidth() / 2 - view.getWidth() / 2 - originalLoc[0];
int yMove = root.getHeight() / 2 - view.getHeight() / 2 - originalLoc[1];
TranslateAnimation anim = new TranslateAnimation( 0, xMove , 0, yMove );
anim.setDuration(1000);
anim.setFillAfter( true );
view.startAnimation(anim);
}
/**
* To get the status bar height.
* #return
*/
private int getStatusBarHeight() {
int result = 0;
int resourceId = getResources().getIdentifier(
"status_bar_height", "dimen", "android");
if (resourceId > 0) {
result = getResources().getDimensionPixelSize(resourceId);
}
return result;
}

I want to display the image view at different position on the screen randomly

Here the ImageView is displaying only at one position, after closing the activity the next time the activity is opened the ImageView will be on another position... I want to display the ImageView randomly at diff position on the same activity itself. The image view should appear on one point suddenly the next second ImageView should disappear from that position and appear on the next position. How can i do it?
public class page2 extends ActionBarActivity {
ImageView b2;
int count = 0;
Handler handler = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_page2);
Intent c = getIntent();
String name = c.getStringExtra("t");
Toast.makeText(getApplicationContext(), name, Toast.LENGTH_SHORT).show();
b2 = (ImageView) findViewById(R.id.redball);
AbsoluteLayout.LayoutParams absParams =
(AbsoluteLayout.LayoutParams)b2.getLayoutParams();
DisplayMetrics displaymetrics = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(displaymetrics);
int width = displaymetrics.widthPixels;
int height = displaymetrics.heightPixels;
Random r = new Random();
absParams.x = r.nextInt(width ) ;
absParams.y = r.nextInt(height );
b2.setLayoutParams(absParams);
Animation animation = AnimationUtils.loadAnimation(page2.this, R.anim.fade);
// Animation animation1 = AnimationUtils.loadAnimation(getApplicationContext(), R.anim.activity_move);
b2.startAnimation(animation);
// b2.startAnimation(animation1);
b2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
count = count + 1;
}
});
handler = new Handler();
final Runnable t = new Runnable() {
public void run() {
Intent d = new Intent(getApplicationContext(), Page3.class);
d.putExtra("count", count);
d.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(d);
}
};
handler.postDelayed(t, 4000);
}
#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_page2, menu);
return true;
}
Don't use AbsoluteLayout, Why not use a custom view draw it?
You can achieve this by using Imageview within FrameLayout. Just change the layoutParams of the image to change its position.
As I understand it, you want that each time the activity is opened, so f you dont want to actually view to the user that the ImageView moves, why are you using Animation? You may just dynamically add the ImageView to the activity each time, and each time assign it different Margin attributes.
LinearLayout layout = (LinearLayout) view.findViewById(R.id.linear);
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
LayoutParams.FILL_PARENT,LayoutParams.WRAP_CONTENT);
params.setMargins(0, 0, 10, 0); //substitute parameters for left, top, right, bottom
ImageView iv = new ImageView(getActivity());
iv.setLayoutParams(params);
iv.setImageResource(R.drawable.yourimage);
layout.addView(iv);
for calucation
ContainerHeight = blinkerContainer.getHeight(); // total height of screen
ContainerWidth = blinkerContainer.getWidth(); //total width
blinkerHeight = blinkView.getHeight();
blinkerWidth = blinkView.getWidth();
minTopMargin = 30;
minLeftMargin = 30;
maxTopMargin = ContainerHeight - blinkerHeight - 30;
maxLeftMargin = ContainerWidth - blinkerWidth - 30;
for positioning
LinearLayout.LayoutParams params = (android.widget.LinearLayout.LayoutParams) blinkView
.getLayoutParams();
params.leftMargin = minLeftMargin
+ new Random().nextInt(maxLeftMargin - minLeftMargin);
params.topMargin = minTopMargin
+ new Random().nextInt(maxTopMargin - minTopMargin);
and you can use AlaramManager for Scheduling
Your solution is almost correct. Unfortunately, it looks like you're restarting the activity from your timer. Instead, you should just trigger the redraw.
This question has a couple of solutions on how to create a recurring timer. The solution with runOnUiThread() should allow you to execute the randomisation and re-displaying of the ImageView.

Android: add textview in a RelativeLayout in random position

I'm adding some textview in a RelativeLayout called "number_container", this is my code but i don't see nothing, the textviews are not added...
private void labelAnimation(){
TextView number = new TextView(getApplicationContext());
number.setGravity(Gravity.CENTER);
Typeface font = Typeface.createFromAsset(getAssets(), "fonts/Gang of Three.ttf");
number.setTypeface(font);
Random random = new Random();
int random_size = random.nextInt(170 - 30) + 30;
number.setTextSize(random_size);
number.setTextColor(000000);
int random_text = random.nextInt(10-1)+1;
number.setText(Integer.toString(random_text));
int random_width = random.nextInt(width_screen - 50) + 50;
int random_height = random.nextInt(height_screen - 50) + 50;
RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT,RelativeLayout.LayoutParams.WRAP_CONTENT);
lp.setMargins(random_width, random_height, 0, 0);
number.setLayoutParams(lp);
number_container.addView(number);
int random_delay = random.nextInt(800-100)+100;
final Handler animation_sun = new Handler();
animation_sun.postDelayed(new Runnable() {
#Override
public void run() {
labelAnimation();
}
}, random_delay);
}
I tried also to remove the custom font but no good results.
What can I do?
My problem was the color of the textView...
number.setTextColor(color.WHITE);

how to get the particular sub view id from the view in android?

I created a dynamic view that contains FrameLayout, and it contains ImageViews. Now, when I touch the particular image on frame layout, I want know the ID of the ImageView.
So, here are my questions:
How can I set the ID for the ImageView?
How can I recognize particular ImageView is touched?
Here is the sample snippet of the code:
for (int j = 0; j < _pageslist.size(); j++) {
FrameLayout frame = new FrameLayout(HLActivity.this);
LayoutParams params = new FrameLayout.LayoutParams(
LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);
frame.setLayoutParams(params);
ImageView mainimage = new ImageView(HLActivity.this);
mainimage.setImageBitmap(ReusableMethods.getBitmapFromURL(_pageslist.get(j)
.getThumbnail().toString()));
mainimage.setScaleType(ScaleType.FIT_XY);
mainimage.setLayoutParams(params);
frame.addView(mainimage, params);
if (_pageslist.get(j).isHasspots()) {
System.out.println(_pageslist.get(j).isHasspots());
System.out.println(_pageslist.get(j).getSPOTS());
ArrayList<Hotspot> hotspots_array = _pageslist.get(j).getSPOTS();
for (int i = 0; i < hotspots_array.size(); i++) {
Hotspot hotspot = hotspots_array.get(i);
System.out.println("hotspot :: " + hotspot.getType());
ImageView spotimage = new ImageView(HLActivity.this);
spotimage.setBackgroundColor(Color.parseColor("#88676767"));
float startx, starty, endx, endy;
startx = (float) (Float.parseFloat(hotspot.getX()) * ivw) / 100;
starty = (float) (Float.parseFloat(hotspot.getY()) * ivh) / 100;
endx = (float) ((Float.parseFloat(hotspot.getX()) +
Float.parseFloat(hotspot.getWidth())) * ivw) / 100;
endy = (float) ((Float.parseFloat(hotspot.getY()) +
Float.parseFloat(hotspot.getHeight())) * ivh) / 100;
params = new FrameLayout.LayoutParams(
(int) ((Float.parseFloat(hotspot.getWidth()) * ivw)/100),
(int) ((Float.parseFloat(hotspot.getHeight()) * ivh)/100));
params.leftMargin = (int) startx;
params.topMargin = (int) starty;
frame.addView(spotimage, params);
}
}
_view.add(frame);
}
adapter = new ViewPagerAdapter(HLActivity.this, _view,
_pageslist, ivw, ivh, getStatusBarHeight());
viewPager.setAdapter(adapter);
you have to set ontouch listener to your image:
yourImage.setOnTouchListener(new OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent arg1) {
// this is your id you can pass it
v.getId()
// TODO Auto-generated method stub
return false;
}
});
If you only want to identify the view which is touched, you can add listeners to your dynamic image views also. Like below
spotimage.setOnClickListener(new OnClickListener() {`
#Override
public void onClick(View v) {
}
});
and in the onClick methord you can write code specific to each image view, or if you strictly want to set the id for image views, you can use spotimage.setId(1)
Id can be any integer value, but you have to make sure no conflict will occur with other id values. and in any listener like OnClickListenet, you can check the image view id byint temp = view.getId();

Categories

Resources