Change TextureView Size at Runtime - java

I am working on streaming a mp4 to a textureView for a app i am currently working on. i have the TextureView displaying the video however i need to resize it to match the screen size on rotation. After much trial and error it seems that the problem is that the TextureView cannot be made larger than the containing view. I have also tried to resize the container view but i am then unable to center the TextureView correctly on screen.
public void onOrientationChanged(int orientation) {
if(isLandscape(orientation)){
myTexture.setRotation(-90);
RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
params.width = height;
params.height = (height * 9)/16;
params.addRule(RelativeLayout.CENTER_IN_PARENT, RelativeLayout.TRUE);
myTexture.setLayoutParams(params);
myTexture.getLayoutParams().height = (height * 9)/16;
myTexture.getLayoutParams().width = height;
rl.requestLayout();
rl.invalidate();
rl.recomputeViewAttributes(myTexture);
Log.v("View Size", "Width tex: " + myTexture.getWidth());
Log.v("View Size", "Height tex: " + myTexture.getHeight());
Log.v("View Size", "Width tex parent: " + rl.getWidth());
Log.v("View Size", "Height tex parent : " + rl.getHeight());
}
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MyActivity"
android:id="#+id/mediaParent"
android:layout_centerInParent="true"
android:paddingLeft="0dp"
android:paddingRight="0dp"
android:paddingTop="0dp"
android:paddingBottom="0dp">
<TextureView
android:layout_width="360dp"
android:layout_height="203dp"
android:id="#+id/surface"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true" />
<Button
style="?android:attr/buttonStyleSmall"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="New Button"
android:id="#+id/button"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true" />
</RelativeLayout>

Try This link :
http://www.binpress.com/tutorial/video-cropping-with-texture-view/21
private void initView() {
mTextureView = (TextureView) findViewById(R.id.textureView);
// SurfaceTexture is available only after the TextureView
// is attached to a window and onAttachedToWindow() has been invoked.
// We need to use SurfaceTextureListener to be notified when the SurfaceTexture
// becomes available.
mTextureView.setSurfaceTextureListener(this);
FrameLayout rootView = (FrameLayout) findViewById(R.id.rootView);
rootView.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View view, MotionEvent motionEvent) {
switch (motionEvent.getAction()) {
case MotionEvent.ACTION_UP:
updateTextureViewSize((int) motionEvent.getX(), (int) motionEvent.getY());
break;
}
return true;
}
});
}
private void updateTextureViewSize(int viewWidth, int viewHeight) {
mTextureView.setLayoutParams(new FrameLayout.LayoutParams(viewWidth, viewHeight));
}

Related

Spin ImageView without losing height and width in android studio

i am developing a roulette game for learning while my friend ask me to make spinning wheel shape from circle to oval. after changing shape of ImageView to an oval and trying to rotate ,it's height and width are swapping according to each 90-degree rotation. while height and width should not change as i need, following are codes i am using and screenshot attached
thanks for your time .
layout_main.xml
<?xml version="1.0" encoding="utf-8"?>
<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=".MainActivity">
<FrameLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/iframe"
android:layout_centerInParent="true">
<ImageView
android:layout_width="wrap_content"
android:layout_height="150dp"
android:src="#drawable/wheel2min_300x300"
android:scaleType="fitXY"
android:id="#+id/wheel_image"
android:layout_centerInParent="true"
android:layout_gravity="center_horizontal"
android:layout_marginTop="25dp"/>
<ImageView
android:layout_width="50dp"
android:layout_height="40dp"
android:src="#drawable/target_147x300"
android:scaleType="fitXY"
android:id="#+id/wheel_pointer"
android:layout_centerInParent="true"
android:layout_gravity="center_horizontal"/>
</FrameLayout>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="press to spin"
android:id="#+id/spin_button"
android:layout_below="#id/iframe"
android:layout_centerHorizontal="true"
android:layout_marginTop="15dp" />
</RelativeLayout>
MainActivity.java
public class MainActivity extends AppCompatActivity {
private ImageView imageView;
private Button button;
int h,w;
CountDownTimer countDownTimer;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
imageView = findViewById(R.id.wheel_image);
button = findViewById(R.id.spin_button);
h=imageView.getHeight();
w = imageView.getWidth();
Random random = new Random();
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
button.setEnabled(false);
// reading random value between 10 to 30
int spin = random.nextInt(20)+10;
// since the wheel has 10 divisions, the
// rotation should be a multiple of
// 360/10 = 36 degrees
spin = spin * 36;
// timer for each degree movement
countDownTimer = new CountDownTimer(spin*20,1) {
#Override
public void onTick(long l) {
// rotate the wheel
float rotation = imageView.getRotation() + 2;
imageView.setRotation(rotation);
}
#Override
public void onFinish() {
// enabling the button again
button.setEnabled(true);
}
}.start();
}
});
}
UI i want even when rotation

Android - Motion Layout or animation item to cart

I'm planning to create an animation like all those apps that have a RecyclerView and when click Add to cart does like a screenshot of the item and with animations goes through the screen and ends in the cart icon.
And I'm wondering if the Motion Layout is something I need to use no matter what, I know you can control the scenes and everything but perhaps there's another way to do this.
The scenario is :
I have a horizontal scroll view and in one item I have a button that says Add to cart, when I press to it then it animates to another view adding alpha until alpha is 0.
The naming of this animation is seen as Fly to cart animation.
Any hint?
This is my custom view and what I want is when I press the button of an item of my RecyclerView this exact item make it smaller and "fly" with a parabola or something or even a straight line to the number 2 making the item smaller and reducing alpha until it arrives to number 2 and it dissapear, and then animate this 2. When the item arrives to the item 2 it should move the second to the first item like the item was removed.
The idea is something like this : https://www.youtube.com/watch?v=YOsz8_vkfiM&ab_channel=AravindrajPalani but instead of doing a "screenshoot" moving the item it self or perhaps I have to hide the item and then create a copy of it... I don't know
Do you mean somthing like this?
Here is How I do it
view_card.xml
Just a typical layout there is no important code here
<?xml version="1.0" encoding="utf-8"?>
<androidx.cardview.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="#+id/card"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
app:cardBackgroundColor="#E6EFF1"
app:cardCornerRadius="12dp"
app:cardUseCompatPadding="true">
<androidx.constraintlayout.widget.ConstraintLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<Button
android:id="#+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="12dp"
android:layout_marginTop="4dp"
android:layout_marginEnd="16dp"
android:text="Add To Cart"
android:textSize="11sp"
app:layout_constraintBottom_toBottomOf="#+id/imageView"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toEndOf="#+id/imageView"
app:layout_constraintTop_toBottomOf="#+id/textView"
app:layout_constraintVertical_bias="1.0" />
<ImageView
android:id="#+id/imageView"
android:layout_width="80dp"
android:layout_height="80dp"
android:layout_marginStart="16dp"
android:layout_marginTop="12dp"
android:layout_marginBottom="12dp"
android:src="#drawable/a2"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<TextView
android:id="#+id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="AIMAN"
android:textAlignment="center"
android:textColor="#color/black"
android:textSize="20dp"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.0"
app:layout_constraintStart_toStartOf="#+id/button"
app:layout_constraintTop_toTopOf="#+id/imageView" />
</androidx.constraintlayout.widget.ConstraintLayout>
</androidx.cardview.widget.CardView>
activity_main.xml
Just a typical layout there is no important code here
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout 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=".MainActivity">
<RelativeLayout
android:id="#+id/card"
android:layout_width="130dp"
android:layout_height="100dp"
android:layout_marginTop="#dimen/cardMargin"
app:cardBackgroundColor="#EDEAF1"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.943"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent">
<ImageView
android:layout_width="40dp"
android:layout_height="40dp"
android:layout_centerInParent="true"
android:src="#drawable/ic_cart" />
</RelativeLayout>
<androidx.recyclerview.widget.RecyclerView
android:id="#+id/recyclerView"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_marginTop="16dp"
android:clipToPadding="false"
android:orientation="horizontal"
android:padding="16dp"
app:layoutManager="androidx.recyclerview.widget.LinearLayoutManager"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.0"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/card"
tools:listitem="#layout/view_card" />
</androidx.constraintlayout.widget.ConstraintLayout>
CustomAdapter.java
Focus here on the remove(..) function, here when you notify by the function notifyItemRemoved(position) the animation after the card removes going to be applied, you don't need to do anything else.
List<Drawable> list;
CustomViewListener listener;
public CustomAdapter() {
list = new ArrayList<>();
}
public void setListener(CustomViewListener listener) {
this.listener = listener;
}
public void add(Drawable drawable) {
list.add(drawable);
notifyDataSetChanged();
}
#NonNull
#Override
public CustomViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View inflate = LayoutInflater.from(parent.getContext()).inflate(R.layout.view_card, parent, false);
return new CustomViewHolder(inflate, listener);
}
#Override
public void onBindViewHolder(#NonNull CustomViewHolder holder, int position) {
holder.bind(list.get(position));
}
#Override
public int getItemCount() {
return list.size();
}
public void remove(Drawable drawable) {
int position = list.indexOf(drawable);
list.remove(drawable);
notifyItemRemoved(position);
}
public interface CustomViewListener {
void onFly(View view, Drawable drawable, int x, int y, int width, int hight);
}
}
CustomViewHolder.java
Foucse here at the following
initSize() to get the CardView size witch we need later to pass it for the temporary ImageView in the MainActivity
at the binding.button.setOnClickListener we going to get the CardView location and after that we call the function onFly to pass the information we need to the MainActivity
class CustomViewHolder extends RecyclerView.ViewHolder {
int width = 0, height = 0;
Drawable drawable;
CustomAdapter.CustomViewListener listener;
ViewCardBinding binding;
public CustomViewHolder(#NonNull View itemView, CustomAdapter.CustomViewListener listener) {
super(itemView);
binding = ViewCardBinding.bind(itemView);
this.listener = listener;
initSize();
initEvent();
}
private void initSize() {
ViewTreeObserver treeObserver = binding.card.getViewTreeObserver();
treeObserver.addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
#Override
public void onGlobalLayout() {
binding.card.getViewTreeObserver().removeOnGlobalLayoutListener(this);
width = binding.card.getMeasuredWidth();
height = binding.card.getMeasuredHeight();
}
});
}
public void bind(Drawable drawable) {
this.drawable = drawable;
binding.imageView.setImageDrawable(drawable);
binding.card.setVisibility(View.VISIBLE);
}
private void initEvent() {
binding.button.setOnClickListener(view -> {
int[] location = new int[2];
binding.card.getLocationInWindow(location);
int x = location[0];
int y = location[1];
listener.onFly(binding.card, drawable, x, y, width, height);
binding.card.setVisibility(View.INVISIBLE);
});
}
}
MainActivity.java
Foucse here at the following
Inside the function handleAnimateTheCard(..)
1- getTemporaryImageView(..) create temporary ImageView with the width and hight of CardView from the RecyclerView
2- loadBitmapFromView(..) draw inside a BitMap to look like the CardView of the RecyclerView
Inside the function startAnime(..) going to create animations you request by the coordinates of the CardView inside the RecyclerView ,and the RelativeLayout inside the MainActivty, here we have three animation pop up then moving the card with fading
after the second animation finish going to remove the card from the RecyclerView
public class MainActivity extends AppCompatActivity {
ActivityMainBinding binding;
CustomAdapter adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
binding = ActivityMainBinding.inflate(getLayoutInflater());
setContentView(binding.getRoot());
adapter = new CustomAdapter();
LinearLayoutManager layoutManager = new LinearLayoutManager(this, LinearLayoutManager.HORIZONTAL, true);
binding.recyclerView.setLayoutManager(layoutManager);
binding.recyclerView.setAdapter(adapter);
adapter.setListener(this::handleAnimateTheCard);
addSomeData();
}
void handleAnimateTheCard(View view, Drawable drawable, int x, int y, int width, int hight) {
ImageView tempImage = getTemporaryImageView(width, hight);
Bitmap viewBitmap = loadBitmapFromView(view);
tempImage.setImageBitmap(viewBitmap);
// here because the y value not include the toolbar and actionbar hight
DisplayMetrics dm = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(dm);
int topOffset = dm.heightPixels - binding.getRoot().getMeasuredHeight();
y -= topOffset;
int[] location = new int[2];
binding.card.getLocationInWindow(location);
int cartX = location[0] - 100;
int cartY = location[1] - topOffset;
tempImage.setAlpha(1f);
startAnime(tempImage, drawable, x, y, cartX, cartY);
}
private ImageView getTemporaryImageView(int width, int hight) {
ImageView tempImage = new ImageView(MainActivity.this);
binding.getRoot().addView(tempImage);
ViewGroup.LayoutParams params = new ViewGroup.LayoutParams(width, hight);
tempImage.setLayoutParams(params);
return tempImage;
}
private void startAnime(ImageView tempImage, Drawable drawable, int x, int y, int cartX, int cartY) {
ObjectAnimator popAnime = ObjectAnimator.ofFloat(tempImage, "translationX", x, x);
ObjectAnimator popAnime2 = ObjectAnimator.ofFloat(tempImage, "translationY", y, y);
ObjectAnimator popAnime3 = ObjectAnimator.ofFloat(tempImage, "scaleY", 1f, 0.9f, 1.2f);
ObjectAnimator popAnime4 = ObjectAnimator.ofFloat(tempImage, "scaleX", 1f, 0.9f, 1.2f);
AnimatorSet popAnimeSet = new AnimatorSet();
popAnimeSet.setDuration(200).playTogether(popAnime, popAnime2, popAnime3, popAnime4);
ObjectAnimator moveAnime = ObjectAnimator.ofFloat(tempImage, "translationX", x, cartX);
ObjectAnimator moveAnime2 = ObjectAnimator.ofFloat(tempImage, "translationY", y, cartY);
ObjectAnimator moveAnime3 = ObjectAnimator.ofFloat(tempImage, "scaleY", 1.2f, 0.5f);
ObjectAnimator moveAnime4 = ObjectAnimator.ofFloat(tempImage, "scaleX", 1.2f, 0.5f);
AnimatorSet moveAnimeSet = new AnimatorSet();
moveAnimeSet.setDuration(500).playTogether(moveAnime, moveAnime2, moveAnime3, moveAnime4);
moveAnimeSet.setStartDelay(50);
moveAnimeSet.addListener(new AnimatorListenerAdapter() {
#Override
public void onAnimationStart(Animator animation) {
super.onAnimationStart(animation);
tempImage.animate().alpha(0f).setDuration(600);
}
});
AnimatorSet animatorSet = new AnimatorSet();
animatorSet.playSequentially(popAnimeSet, moveAnimeSet);
animatorSet.addListener(new AnimatorListenerAdapter() {
#Override
public void onAnimationEnd(Animator animation) {
super.onAnimationEnd(animation);
adapter.remove(drawable);
}
});
animatorSet.start();
}
public Bitmap loadBitmapFromView(View view) {
Bitmap returnedBitmap = Bitmap.createBitmap(view.getWidth(), view.getHeight(), Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(returnedBitmap);
Drawable bgDrawable = view.getBackground();
if (bgDrawable != null)
bgDrawable.draw(canvas);
else
canvas.drawColor(Color.WHITE);
view.draw(canvas);
return returnedBitmap;
}
private void addSomeData() {
adapter.add(ContextCompat.getDrawable(this, R.drawable.a1));
adapter.add(ContextCompat.getDrawable(this, R.drawable.a2));
adapter.add(ContextCompat.getDrawable(this, R.drawable.a3));
}
}

java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.CardView.setVisibility(int)' on a null object reference

I am trying to animate a Cardview when FAB is pressed. I want to get circular animation. Initially Cardview is set to Invisible. But, it is trowing null object reference on CardView.setVisibility.
public class FeedFragment extends Fragment {
private FloatingActionButton floatingBtn;
private CardView cardView;
boolean flag = true;
public FeedFragment() {
// Required empty public constructor
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_feed, container, false);
floatingBtn = view.findViewById(R.id.floatBtn);
cardView = view.findViewById(R.id.cardView);
floatingBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if(flag) {
// Check if the runtime version is at least Lollipop
if (Build.VERSION.SDK_INT == Build.VERSION_CODES.LOLLIPOP) {
// get the center for the clipping circle
int cx = cardView.getWidth() / 2;
int cy = cardView.getHeight() / 2;
// get the final radius for the clipping circle
float finalRadius = (float) Math.hypot(cx, cy);
// create the animator for this view (the start radius is zero)
Animator anim =
ViewAnimationUtils.createCircularReveal(cardView, cx, cy, 0, finalRadius);
// make the view visible and start the animation
cardView.setVisibility(View.VISIBLE);
anim.start();
} else {
// set the view to visible without a circular reveal animation below Lollipop
cardView.setVisibility(View.VISIBLE);
}
flag = false;
} else {
// Check if the runtime version is at least Lollipop
if (Build.VERSION.SDK_INT == Build.VERSION_CODES.LOLLIPOP) {
// get the center for the clipping circle
int cx = cardView.getWidth() / 2;
int cy = cardView.getHeight() / 2;
// get the initial radius for the clipping circle
float initialRadius = (float) Math.hypot(cx, cy);
// create the animation (the final radius is zero)
Animator anim =
ViewAnimationUtils.createCircularReveal(cardView, cx, cy, initialRadius, 0);
// make the view invisible when the animation is done
anim.addListener(new AnimatorListenerAdapter() {
#Override
public void onAnimationEnd(Animator animation) {
super.onAnimationEnd(animation);
cardView.setVisibility(View.INVISIBLE);
}
});
// start the animation
anim.start();
} else {
// set the view to visible without a circular reveal animation below Lollipop
cardView.setVisibility(View.VISIBLE);
}
flag = true;
}
}
});
return view;
}
}
Here is the XML code
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
xmlns:app="http://schemas.android.com/apk/res-auto"
tools:context="com.authent.authentication.FeedFragment">
<!-- TODO: Update blank fragment layout -->
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:layout_gravity="bottom">
<android.support.v7.widget.CardView
android:id="#+id/cardView"
android:layout_width="match_parent"
android:layout_height="208dp"
android:layout_gravity="bottom"
android:layout_marginBottom="8dp"
android:layout_marginEnd="16dp"
android:layout_marginRight="16dp"
android:layout_marginStart="16dp"
app:cardCornerRadius="20dp"
android:visibility="gone">
<LinearLayout
android:id="#+id/linearReveal"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:visibility="gone">
<Button
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1"
android:background="#color/white"
android:text="Ask a Query"
android:textSize="24dp"
android:textAllCaps="false"
android:textColor="#00ccff"/>
<View
android:layout_width="match_parent"
android:layout_height="1dp"
android:background="#android:color/darker_gray"/>
<Button
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1"
android:background="#color/white"
android:text="Share Something"
android:textSize="24dp"
android:textAllCaps="false"
android:textColor="#ff3300"/>
<View
android:layout_width="match_parent"
android:layout_height="1dp"
android:background="#android:color/darker_gray"/>
<Button
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1"
android:background="#color/white"
android:text="Post an MCQ"
android:textSize="24dp"
android:textAllCaps="false"
android:textColor="#cc9900"/>
</LinearLayout>
</android.support.v7.widget.CardView>
<android.support.design.widget.FloatingActionButton
android:id="#+id/floatBtn"
android:layout_width="56dp"
android:layout_height="56dp"
android:layout_gravity="end"
android:layout_marginEnd="16dp"
android:layout_marginBottom="16dp"
android:layout_marginRight="16dp"
android:src="#drawable/edit_nick_name" />
</LinearLayout>
Somebody help how to achieve circular animation. I am new to programming.
I also tried making LinearLayout INVISIBLE, it is also throwing NullPointerException on LinearLayout.setVisibility on a null object reference.
Thanks in advance.
Your CardView is null. Based on your code, you are trying to get the CardView from the View that received the onClick which is the FloatingButton.
Try calling the initialization outside just before the listener. Ideally on the same level as where you initialized the FloatingButton.
Intilaize cardview outside of the "clickListener".
You just need to remove this line cardView = view.findViewById(R.id.cardView);
and paste it before
floatingBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
return view;
}

How to fade ImageView after drag/drop is done?

I have one ImageView (drag and drop) and one button that fades the Image. drag and drop works fine and fade button initially works fine to. The issue arises when the image is dragged and THEN fade button is pressed.
it seems that it only fades the original place the image was(before drag and drop). I would like to fade the actual image after its been dragged. Here is a picture explaining :enter image description here
my main_activity.xml:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context="app.com.example.muhammad.downloadmanagerexample.MainActivity">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!"
android:id="#+id/Hello"/>
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/imageView"
android:src="#drawable/images"
android:layout_centerVertical="true"
android:layout_centerHorizontal="true" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Fade"
android:id="#+id/buttonFade"
android:layout_below="#+id/imageView"
android:layout_centerHorizontal="true"
android:layout_marginTop="77dp" />
</RelativeLayout>
MainActivity.java
public class MainActivity extends AppCompatActivity implements View.OnTouchListener {
ImageView image;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
image = (ImageView) findViewById(R.id.imageView);
//downloadFile(path);
image.setOnTouchListener(this);
Button fadeButton = (Button) findViewById(R.id.buttonFade);
fadeButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
AlphaAnimation animation = new AlphaAnimation(1.0f, 0.0f);
animation.setDuration(1000);
animation.setRepeatCount(1);
animation.setRepeatMode(Animation.REVERSE);
image.startAnimation(animation);
//appIcon.animate().alpha(0.0f).setDuration(1000);
//appIcon.animate().alpha(1.0f).setDuration(1000);
}
});
}
PointF DownPT = new PointF(); // Record Mouse Position When Pressed Down
PointF StartPT = new PointF(); // Record Start Position of 'img'
#Override
public boolean onTouch(View v, MotionEvent event) {
int eid = event.getAction();
switch (eid)
{
case MotionEvent.ACTION_MOVE :
PointF mv = new PointF( event.getX() - DownPT.x, event.getY() - DownPT.y);
image.setX((int)(StartPT.x+mv.x));
image.setY((int)(StartPT.y+mv.y));
StartPT = new PointF( image.getX(), image.getY() );
break;
case MotionEvent.ACTION_DOWN :
DownPT.x = event.getX();
DownPT.y = event.getY();
StartPT = new PointF( image.getX(), image.getY() );
break;
case MotionEvent.ACTION_UP :
// Nothing have to do
break;
default :
break;
}
return true;
}
}
I have been searching about this topic and couldn't find an excat solution so thought about asking it. Thank you in advance. really appreciate this site and all of the people who contribute to it :)
you actually create new image every time.You are not dealing with one image only.You do not have same instance of image.when you fade you are deleting image.And when you drop image after dragging then you recreate image.If you find my answer appropriate then upvote me.Thanks

Android layout Not working

Hii i made a simple layout in which i use 3 image views and i make the center one movable.
Her is my layout class main.xml:-
<?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" >
<view class="com.example.screenlock.MainActivity$IV"
android:id="#+id/image"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:scaleType="center"
/>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="bottom|fill_horizontal"
android:background="#60000000"
android:orientation="horizontal"
android:padding="7dp" >
<ImageView
android:id="#+id/imageView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="0"
android:scaleType="fitXY"
android:layout_alignParentLeft="true"
android:src="#drawable/browser1" />
<ImageView
android:id="#+id/imageView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:src="#drawable/circle" />
<ImageView
android:id="#+id/imageView3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="right|fill_vertical"
android:layout_weight="0"
android:scaleType="fitXY"
android:src="#drawable/lock" />
</LinearLayout>
</FrameLayout>
and My MainActivity.java class is as follows:-
public class MainActivity extends Activity {
private ImageView imageView1, imageView2;
public static class IV extends ImageView {
private MainActivity mActivity;
public IV(Context context) {
super(context);
}
public IV(Context context, AttributeSet attrs) {
super(context, attrs);
}
public void setActivity(MainActivity act) {
mActivity = act;
}
public void onSystemUiVisibilityChanged(int visibility) {
mActivity.getState().onSystemUiVisibilityChanged(visibility);
}
}
private interface State {
void apply();
State next();
void onSystemUiVisibilityChanged(int visibility);
}
State getState() {
return mState;
}
static int TOAST_LENGTH = 500;
IV mImage;
TextView mText1, mText2;
State mState;
public MainActivity() {
// TODO Auto-generated constructor stub
}
#Override
protected void onCreate(Bundle savedInstanceState) {
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
super.onCreate(savedInstanceState);
//setContentView(R.layout.activity_main);
getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON|WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED|WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.activity_main);
startService(new Intent(this, MyLockService.class));
System.out.println(R.id.image);
imageView2 = (ImageView)findViewById(R.id.imageView2);
imageView2.setOnTouchListener(new OnTouchListener()
{
float lastX;
PointF DownPT = new PointF(); // Record Mouse Position When Pressed Down
PointF StartPT = new PointF(); // Record Start Position of 'img'
#SuppressLint("NewApi")
#Override
public boolean onTouch(View v, MotionEvent event)
{
int eid = event.getAction();
switch (eid)
{
case MotionEvent.ACTION_MOVE :
PointF mv = new PointF( event.getX() - DownPT.x, event.getY() - DownPT.y);
if(Build.VERSION.SDK_INT <= Build.VERSION_CODES.GINGERBREAD){
v.scrollBy((int) (event.getX()-lastX), 0);
lastX = event.getX();
if(lastX >= 170){
MarginLayoutParams lp = (MarginLayoutParams) imageView2.getLayoutParams();
lp.setMargins(178, 0, 0, 0);
imageView2.setLayoutParams(lp);
}
if(lastX <= 25){
MarginLayoutParams lp = (MarginLayoutParams) imageView2.getLayoutParams();
lp.setMargins(0, -16, 0, 0);
imageView2.setLayoutParams(lp);
}
System.out.println("XXXXXXX "+lastX);
}
else{
imageView2.setX((int)(StartPT.x+mv.x));
imageView2.setY((int)(StartPT.y+mv.y));
StartPT = new PointF( imageView2.getX(), imageView2.getY() );
//System.out.println("X: "+imageView2.getX()+"Y: "+imageView2.getY());
if(imageView2.getX() < -70)
{
imageView2.setX(-103);
imageView2.setY(6);
//System.out.println("--------------------------------------");
}
else if(imageView2.getX() > 260)
{
imageView2.setX(270);
imageView2.setY(8);
finish();
}
}
break;
case MotionEvent.ACTION_DOWN :
if(Build.VERSION.SDK_INT <= Build.VERSION_CODES.GINGERBREAD){
lastX = event.getX();
}
else{
DownPT.x = event.getX();
DownPT.y = event.getY();
StartPT = new PointF( imageView2.getX(), imageView2.getY() );
}
break;
case MotionEvent.ACTION_UP :
v.scrollTo(0, 0);
break;
default :
break;
}
return true;
}
});
}
public void onWindowFocusChanged(boolean hasFocus) {
super.onWindowFocusChanged(hasFocus);
// Use onWindowFocusChanged to get the placement of
// the image because we have to wait until the image
// has actually been placed on the screen before we
// get the coordinates. That makes it impossible to
// do in onCreate, that would just give us (0, 0).
imageView1 = (ImageView) findViewById(R.id.imageView1);
int[] a = new int[2];
imageView1.getLocationInWindow(a);
int x = a[0];
int y = a[1];
System.out.println("X "+x+" Y "+y);
}
}
#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;
}
}
I am executing this code on pre-honeycomb emulator. But when i move the center image it gets hides behind the left and right images respectively.
I want center image to shown on the rest of two images and also want to show that two images also.
Basically, the center image is a circle and rest two images are browser and lock images and i want that circle to overlaps that images.
I am working on a lock screen.
Please help in my layout problem and how i can solve this problem?????
You can try changing your layout as follows...
<?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" >
<view
android:id="#+id/image"
android:layout_width="match_parent"
android:layout_height="match_parent"
class="com.example.screenlock.MainActivity$IV"
android:scaleType="center" />
<FrameLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="bottom|fill_horizontal" >
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#60000000"
android:orientation="horizontal"
android:padding="7dp" >
<ImageView
android:id="#+id/imageView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="0"
android:scaleType="fitXY"
android:src="#drawable/ic_launcher" />
<View
android:layout_width="0dip"
android:layout_height="wrap_content"
android:layout_weight="1" />
<ImageView
android:id="#+id/imageView3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="right|fill_vertical"
android:layout_weight="0"
android:scaleType="fitXY"
android:src="#drawable/ic_launcher" />
</LinearLayout>
<ImageView
android:id="#+id/imageView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:src="#drawable/ic_launcher" />
</FrameLayout>
</FrameLayout>

Categories