I want to move ImageView (man.png) from right to left in Activity class(implements Runnable). I am using
Man.setTranslationX(float x); to move... Here is my code Man is not moving by run() method ..
public class PlayScreen extends Activity implements Runnable{
float ManX=100;
Thread thread=new Thread(this);
//some code here(removed)
public void ManImageView() {
Man = (ImageView)findViewById(R.id.stickman);
Man.setVisibility(ImageView.VISIBLE);
thread.start();
}
#Override
public void run(){
Man.setTranslationX(ManX);
ManX++;
try{
thread.sleep(500);}
catch{
}
}
is there any way to update ur screen continuously like invalidate(); method in View class.. or there is some problem with Thread running??? Here is .xml of ImageView
<ImageView
android:id="#+id/stickman"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_alignParentLeft="true"
android:layout_marginLeft="50sp"
android:layout_marginBottom="15sp"
android:src="#drawable/image1"/>
Please Help
Related
I'm stuck and need help.
How can I add animations like on the picture. I want the color of the background and text to be smoothly automatically changed 1 sec after the app is launched. And to be like a cycle. Meanwhile an icon is impulsing.
You can use Property Animation for changing color
int colorFrom = getResources().getColor(R.color.red);
int colorTo = getResources().getColor(R.color.blue);
ValueAnimator colorAnimation = ValueAnimator.ofObject(new ArgbEvaluator(), colorFrom, colorTo);
colorAnimation.setDuration(500); // milliseconds
colorAnimation.addUpdateListener(new AnimatorUpdateListener() {
#Override
public void onAnimationUpdate(ValueAnimator animator) {
textView.setBackgroundColor((int) animator.getAnimatedValue());
}
});
colorAnimation.start();
Use alpha animations to fade in and out the textchanging So on repeat is when it is fading back in so you can update the text at that time
AlphaAnimation anim = new AlphaAnimation(1.0f, 0.0f);
anim.setDuration(500);
anim.setRepeatCount(1);
anim.setRepeatMode(Animation.REVERSE);
txtLabel.startAnimation(anim);
anim.setAnimationListener(new Animation.AnimationListener() {
#Override
public void onAnimationStart(Animation animation) {
}
#Override
public void onAnimationEnd(Animation animation) {
}
#Override
public void onAnimationRepeat(Animation animation) {
txtLabel.setText("my next Text"); //for fading back in
}
});
You can use the same animation for alpha on a bitmap or imageView to pulse in and out as well.
AlphaAnimation animPulse = new AlphaAnimation(1.0f, 0.0f);
animPulse.setDuration(500);
animPulse.setRepeatCount(Animation.INFINITE);
animPulse.setRepeatMode(Animation.REVERSE);
imgPulse.startAnimation(animPulse);
Then of course just put in your
public void onCreate(){
Handler mMainHandler = new Handler(Looper.prepareMainLooper());
mMainHandler.postDelay(new Runnable(){
doAnimations();
}, 1000);
}
Then simply lump all your animations into methods and call them from doAnimations. Good luck.
Here you go..
I did the code to change color of background layout and text. Currently I did for random colors, if you need pre-defined colors, please let me know. Below is my code
activity_main.xml
`
<android.support.constraint.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="com.example.golevr.background_animation.MainActivity"
android:id="#+id/constraint">
<TextView
android:id="#+id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!"
android:textSize="30dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</android.support.constraint.ConstraintLayout>
`
MainActivity.java
`
public class MainActivity extends AppCompatActivity {
// Move your declarations here if you intend on using them after the onCreate() method
ConstraintLayout layout;
TextView textView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Inflate your objects
layout = (ConstraintLayout) findViewById(R.id.constraint);
textView = (TextView) findViewById(R.id.textView);
// We change the color to RED for the first time as the program loads
layout.setBackgroundColor(Color.RED);
// We change the color to GREEN for the first time as the program loads
textView.setTextColor(Color.GREEN);
// Create the timer object which will run the desired operation on a schedule or at a given time
Timer timer = new Timer();
// Create a task which the timer will execute. This should be an implementation of the TimerTask interface.
// I have created an inner class below which fits the bill.
MyTimer myTimer = new MyTimer();
// We schedule the timer task to run after 1000 ms and continue to run every 1000 ms.
timer.schedule(myTimer,1000,1000);
}
// An inner class which is an implementation of the TImerTask interface to be used by the Timer.
class MyTimer extends TimerTask{
#Override
public void run() {
// This runs in a background thread.
// We cannot call the UI from this thread, so we must call the main UI thread and pass a runnable
runOnUiThread(new Runnable() {
#Override
public void run() {
Random rand = new Random();
// The random generator creates values between [0,256) for use as RGB values used below to create a random color
// We call the RelativeLayout object and we change the color. The first parameter in argb() is the alpha.
layout.setBackgroundColor(Color.argb(255, rand.nextInt(256),rand.nextInt(256),rand.nextInt(256)));
textView.setTextColor(Color.argb(222,rand.nextInt(222),rand.nextInt(222),rand.nextInt(222)));
}
});
}
}
}
`
Is this what you want?
I have a RecyclerView with ImageViews in each item.
I set onClickListener for the ImageViews in onBindViewHolder as follows:
holder.starIV.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO: logic
}
});
The ripple effect worked fine until I added the following logic to onClick. This logic changes the Drawable for the ImageView.
holder.starIV.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (v.getId() == holder.starIV.getId()) {
ListItem clickedItem = mDataset.get(position);
ListItem updatedItem = new ListItem(clickedItem);
if (clickedItem.getStarState() == STAR_ON) {
updatedItem.setStarState(STAR_OFF);
updatedItem.setStarDrawable(
ContextCompat.getDrawable(
v.getContext(),R.drawable.ic_star_border_24px));
}
else if (clickedItem.getStarState() == STAR_OFF) {
updatedItem.setStarState(STAR_ON);
updatedItem.setStarDrawable(
ContextCompat.getDrawable(
v.getContext(),R.drawable.ic_star_24px));
}
mDataset.set(position,updatedItem);
notifyDataSetChanged();
}
}
});
Now, I get no ripple effect at all. Here's the XML for the ImageView:
<ImageView
android:id="#+id/list_item_star"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1"
android:paddingLeft="4dp"
android:paddingRight="16dp"
android:src="#drawable/ic_star_border_24px"
android:clickable="true"
android:background="?attr/selectableItemBackgroundBorderless"
android:drawSelectorOnTop="true"
/>
The ripple effect works normally again when i comment out the logic part in onClick.
Have I implemented the above correctly?
What change would you suggest to get the ripple effect working correctly?
EDIT: It appears that changing the Drawable is interfering with the ripple animation. So i moved all the logic to an AsyncTask with a small delay to allow the animation to finish. This seems to work, but I feel this solution is not elegant. Here's the AsyncTask:
class DoLogix extends AsyncTask<Integer, Integer, Void> {
#Override
protected Void doInBackground(Integer... params) {
try{Thread.sleep(125);}catch (Exception e) {}
publishProgress(params[0]);
return null;
}
protected void onProgressUpdate(Integer... val) {
ListItem clickedItem = mDataset.get(val[0]);
ListItem updatedItem = new ListItem(clickedItem);
if (clickedItem.getStarState() == STAR_ON) {
updatedItem.setStarState(STAR_OFF);
updatedItem.setStarDrawable(starBorder);
}
else if (clickedItem.getStarState() == STAR_OFF) {
updatedItem.setStarState(STAR_ON);
updatedItem.setStarDrawable(star);
}
mDataset.set(val[0],updatedItem);
notifyDataSetChanged();
}
}
u can set a ripple drawable as the foreground of ur imageview.
add below code to your parent layout
android:clickable="true"
android:focusable="true"
android:background="?attr/selectableItemBackgroundBorderless"
I have made an array that has all the images in int and i want to change those images every 3 seconds in the imageView, I have tries all the solutions I could find but was showing some error, I can't figure it out .
java file (home.java)
/**
* Created by sukhvir on 17/04/2015.
*/
public class home extends android.support.v4.app.Fragment {
ImageView MyImageView;
int[] imageArray = { R.drawable.image1, R.drawable.image2, R.drawable.image3, R.drawable.image4, R.drawable.image5 };
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
/**
* Inflate the layout for this fragment
*/
return inflater.inflate(R.layout.home, container, false);
}
}
xml file(home.xml)
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">
<ImageView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/imageView"
android:layout_gravity="center_horizontal" />
</LinearLayout>
Best option to achieve your requirement is You should use Timer to change Image each of 3 seconds as follows.
// Declare globally
private int position = -1;
/**
* This timer will call each of the seconds.
*/
Timer mTimer = new Timer();
mTimer.schedule(new TimerTask() {
#Override
public void run() {
// As timer is not a Main/UI thread need to do all UI task on runOnUiThread
getActivity().runOnUiThread(new Runnable() {
#Override
public void run() {
// increase your position so new image will show
position++;
// check whether position increased to length then set it to 0
// so it will show images in circuler
if (position >= imageArray.length)
position = 0;
// Set Image
MyImageView.setImageResource(imageArray[position]);
}
});
}
}, 0, 3000);
// where 0 is for start now and 3000 (3 second) is for interval to change image as you mentioned in question
use a CountDownTimer here is how: How to make a countdown Timer in android?
and change the image view background inside onFinish().
hope this will work out for you
first define a runnable
private Runnable runnable = new Runnable() {
#Override
public void run() {
changeImage(pos);
}
};
Than create a handler
private Handler handler;
handler = new Handler(Looper.getMainLooper());
In your changeImage method
private void changeImage(int pos) {
yourImageView.setImageResource(imageArray[pos]);
handler.postDelayed(runnable, duration);
}
Start and stop runnable with:
handler.postDelayed(runnable, duration);
handler.removeCallbacks(runnable);
I hope this'll help you. Good luck.
I want to get user input for my OpenGL ES 2.0 application, but there are 2 problems:
1) How can I bring the software keyboard to the front of my app?
2) How can I catch input from it?
I tried to use this:
//OpenGL ES 2.0 view class
public class OGLES2View extends GLSurfaceView
{
private static final int OGLES_VERSION = 2;
private static Handler softKeyboardHandler;
private final static int SHOW_IME_KEYBOARD = 0;
private final static int HIDE_IME_KEYBOARD = 1;
private static EditText textEdit;
private static InputMethodManager imm;
private void setSoftKeyboardHandler()
{
softKeyboardHandler = new Handler()
{
public void handleMessage(Message msg)
{
switch(msg.what)
{
case SHOW_IME_KEYBOARD:
textEdit.requestFocus();
imm.showSoftInput(textEdit,inputMethodManager.SHOW_IMPLICIT);//Nothing happens
Log.i("GLVIEW","SHOW KEYBOARD");
break;
case HIDE_IME_KEYBOARD:
imm.hideSoftInput(textEdit, 0);
Log.i("GLVIEW","HIDE KEYBOARD");
break;
default:
break;
}
}
};
}
public OGLES2View(Context context)
{
super(context);
textEdit = new EditText(context);
setEGLContextClientVersion(OGLES_VERSION);
setRenderer(new OGLES2Renderer());
imm = (InputMethodManager)context.getSystemService(Context.INPUT_METHOD_SERVICE);
setSoftKeyboardHandler();
}
public static void showIMEKeyboard()
{
softKeyboardHandler.sendEmptyMessage(SHOW_IME_KEYBOARD);
}
public static void hideIMEKeyboard()
{
softKeyboardHandler.sendEmptyMessage(HIDE_IME_KEYBOARD);
}
//In main activity class
private GLSurfaceView ogles2SurfaceView = null;
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
//...
ogles2SurfaceView = new OGLES2View(this);
setContentView(ogles2SurfaceView);
}
Handler gets messages, but I got no software keyboard.
To catch text, I wrote some class:
public class TextInputWatcher implements TextWatcher
and:
textEdit.addTextChangedListener(/*TextInputWatcher instance*/);
Or extend a TextEdit so it catches inputed text on back or enter key.
P.S. I got a tablet - transformer, so there is a hardware keyboard attached. I tried with it and without, but no difference. So bonus question - if there is a hardware keyboard will it prevent a software keyboard from popping up and how can input be gotten from it then?.
Show keyboard:
getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE);
Hide keyboard:
getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
I made 2d game. I think you have the same problem like me before. Try this:
class DrawingPanel extends SurfaceView implements SurfaceHolder.Callback {
private static DrawThread _thread;
public DrawingPanel(Context context, AttributeSet attrs) {
super(context, attrs);
getHolder().addCallback(this);
_thread = new DrawThread(getHolder(), this);
}
....
Layout 'gameview':
<FrameLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<!-- YOUR SURFACE -->
<com.yourcompany.DrawingPanel android:id="#+id/surfaceView" android:layout_width="fill_parent"
android:layout_height="fill_parent"></com.yourcompany.DrawingPanel>
<!-- YOUR BUTTONS -->
<RelativeLayout android:id="#+id/controlPanel" android:layout_width="fill_parent" android:orientation="horizontal"
android:layout_height="fill_parent" >
<RelativeLayout android:layout_width="50px" android:orientation="vertical"
android:layout_height="fill_parent" android:gravity="center_vertical" android:layout_alignParentLeft="true">
<Button android:id="#+id/leftButton" android:layout_width="wrap_content"
android:layout_height="50px" android:background="#xml/button_left_state"/>
<Button android:id="#+id/upgradeButton" android:layout_width="wrap_content"
android:layout_below="#id/leftButton"
android:layout_height="50px" android:background="#xml/button_upgrade_state"/>
</RelativeLayout>
</RelativeLayout>
</FrameLayout>
Then you should set content in game activity like below:
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.gameview);
...
Hope It helps you.
I'm currently working on a project where I use a webview packed in RelativeLayout and I placed a ImageButton in the left-bottom corner:
<RelativeLayout
android:id="#+id/relativeLayout_maincontent"
android:layout_width="fill_parent"
android:layout_height="fill_parent" >
<WebView
android:id="#+id/webview"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_alignParentTop="true"
/>
<ImageButton
android:id="#+id/imageButton_call"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_marginLeft="2dp"
android:src="#android:drawable/ic_menu_call" />
</RelativeLayout>
This works just fine. The next step I was thinking of is that the button can sometimes disturb my users, when they can't see the stuff behind the button... So I tried to hide the button after a few seconds and when the user is scrolling/touching/or whatever (just some user input) I'll display it and after a few seconds the button should disappear again. Like the zoom-in and zoom-out buttons in a webview. The best way would be to use the same functionality as these zoom buttons, but I couldn't find a way to do this. I created a function based on the knowledge of How to show a view for 3 seconds, and then hide it? :
private void startCallButtonHidingThread() {
Thread thread = new Thread() {
#Override
public void run() {
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
}
runOnUiThread(new Runnable() {
#Override
public void run() {
callButton.setVisibility(ImageButton.GONE);
}
});
}
};
thread.start();
}
That works great. The next step was to display the button when user input happens, so I tried things like that:
relativeLayout.setOnTouchListener(new OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
if(callButton.getVisibility() == ImageButton.GONE) callButton.setVisibility(ImageButton.VISIBLE);
startCallButtonHidingThread();
return false;
}
});
or that:
relativeLayout.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if(callButton.getVisibility() == ImageButton.GONE) callButton.setVisibility(ImageButton.VISIBLE);
startCallButtonHidingThread();
}
});
and the same I tried on the webview. Most of the time it works just one time and then there is no reaction at all.
So if you have any idea or a better solution, please let me know.
I really appreciate your help!
I think it's android restriction. Try to use handler:
private Handler handler = new Handler(){
#Override
public void handleMessage(Message msg) {
switch (msg.what){
case 1:{
if(callButton.getVisibility() == ImageButton.GONE) callButton.setVisibility(ImageButton.VISIBLE);
startCallButtonHidingThread();
}
}
};
And your listener:
relativeLayout.setOnTouchListener(new OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
handler.sendEmptyMessage(1);
return false;
}
});