I have dynamically created imageView in my ViewFlipper and it runs smoothly. However, when I want to click the image I need to do an enlargement of the image and do something with it. How do i get the id. I need to be able to differentiate which image i have clickeded.
Thanks in advance.
public class Home_Fragment extends Fragment{
.....
private ViewFlipper vf;
int gallery_grid_Images[]={R.drawable.a,R.drawable.b,R.drawable.c,
R.drawable.d};
private void setFlipperImage(int res) {
//Log.i("Set Filpper Called", res+"");
ImageView image = new ImageView(getActivity());
LayoutParams lp = new LayoutParams(LayoutParams.MATCH_PARENT,
LayoutParams.MATCH_PARENT);
image.setLayoutParams(lp);
image.setAdjustViewBounds (true);
image.setScaleType(ScaleType.CENTER_INSIDE);
image.setClickable(true);
image.setBackgroundResource(res);
image.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
int id=(Integer) v.getTag(); //---> This will crash if i click the image
//Toast.makeText(getActivity(), id+"", Toast.LENGTH_LONG).show();
}
});
vf.setTag(res);
vf.addView(image);
}
Below code i have used for viewflipper for sliding image.you can add onclick event of image inside forloop.
SlideShowActivity.java
package com.example.viewpagerexample;
import android.app.Activity;
import android.os.Bundle;
import android.view.MotionEvent;
import android.widget.ImageView;
import android.widget.ViewFlipper;
public class SlideShowActivity extends Activity {
private ViewFlipper myViewFlipper;
private float initialXPoint;
int[] image = { R.drawable.one_full, R.drawable.two_full,
R.drawable.three_full, R.drawable.four_full, R.drawable.five_full,
R.drawable.six_full, R.drawable.seven_full, R.drawable.eight_full,
R.drawable.nine_full, R.drawable.ten_full };
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.slide_show);
myViewFlipper = (ViewFlipper) findViewById(R.id.myflipper);
for (int i = 0; i < image.length; i++) {
ImageView imageView = new ImageView(SlideShowActivity.this);
imageView.setImageResource(image[i]);
myViewFlipper.addView(imageView);
imageView.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// your code
}});
}
#Override
public boolean onTouchEvent(MotionEvent event) {
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
initialXPoint = event.getX();
break;
case MotionEvent.ACTION_UP:
float finalx = event.getX();
if (initialXPoint > finalx) {
if (myViewFlipper.getDisplayedChild() == image.length)
break;
myViewFlipper.showNext();
} else {
if (myViewFlipper.getDisplayedChild() == 0)
break;
myViewFlipper.showPrevious();
}
break;
}
return false;
}
}
Here the images are only changing while user is swipe.
If you want to swipe automatically with certain interval add the following code.
myViewFlipper.setAutoStart(true);
myViewFlipper.setFlipInterval(3000);
myViewFlipper.startFlipping();
To post my research, I am able to know which image I clicked. image.setId(tagNum); tagNum running from 0 to max number of imageView i created-1. when clicked, the number is shown correctly in log. I can use that number to find the image source in my array.
private void setFlipperImage(int res, int tagNum) {
ImageView image = new ImageView(getActivity());
LayoutParams lp = new LayoutParams(LayoutParams.MATCH_PARENT,
LayoutParams.MATCH_PARENT);
image.setLayoutParams(lp);
image.setAdjustViewBounds (true);
image.setScaleType(ScaleType.CENTER_INSIDE);
image.setClickable(true);
image.setBackgroundResource(res);
image.setId(tagNum);
image.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
//vf.getTag(key);
int id = vf.getCurrentView().getId();
Log.d("Value id", Integer.valueOf(id).toString());
}
});
// vf.setTag(res);
vf.addView(image);
}
Why don't you use image.setTag(). Set an unique tag for each imageView and onClick get that tag and determine which imageView you clicked.
int id=(Integer) v.getTag();
The above line crashes may be its getting null.
Hope this helps. :)
Related
I have a Button, TextView(number) and an ImageView. Every time I press the button the number will increment. It will increment a lot faster when I hold the button.
I want to show an image at a specific number using ImageView at the same time making the button visible to INVISIBLE for a while to stop the increment.
The problem: If I press the button one click at a time then the below code functions well but as I hold down the button, the image appears for a very short while and continue with the numbers. And although the button is set invisible for 5 seconds, the numbers still increases(as the button is still hold).
MAIN CLASS
public class MainActivity extends AppCompatActivity {
Button button;
TextView textView;
ImageView imageView;
int i=0;
#SuppressLint("ClickableViewAccessibility")
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
imageView=findViewById(R.id.imageView);
textView=findViewById(R.id.textView);
button = findViewById(R.id.button);
button.setOnTouchListener(new RepeatListener(400, 100, new View.OnClickListener() {
#Override
public void onClick(View view) {
setText();
setImage();
}
}));
}
public void setText(){
imageView.setVisibility(View.INVISIBLE);
textView.setText(""+i);
i++;
}
public void setImage(){
if(i==10){
imageView.setImageResource(R.drawable.kitten);
imageView.setVisibility(View.VISIBLE);
buttonInvi();
}
}
public void buttonInvi(){
button.setVisibility(View.INVISIBLE);
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
button.setVisibility(View.VISIBLE);
}
}, 5000); // where 1000 is equal to 1 sec (1 * 1000)
}
}
RepeatListener CLASS
public class RepeatListener implements OnTouchListener {
private Handler handler = new Handler();
private int initialInterval;
private final int normalInterval;
private final OnClickListener clickListener;
private View touchedView;
private Runnable handlerRunnable = new Runnable() {
#Override
public void run() {
if(touchedView.isEnabled()) {
handler.postDelayed(this, normalInterval);
clickListener.onClick(touchedView);
} else {
// if the view was disabled by the clickListener, remove the callback
handler.removeCallbacks(handlerRunnable);
touchedView.setPressed(false);
touchedView = null;
}
}
};
public RepeatListener(int initialInterval, int normalInterval,
OnClickListener clickListener) {
if (clickListener == null)
throw new IllegalArgumentException("null runnable");
if (initialInterval < 0 || normalInterval < 0)
throw new IllegalArgumentException("negative interval");
this.initialInterval = initialInterval;
this.normalInterval = normalInterval;
this.clickListener = clickListener;
}
public boolean onTouch(View view, MotionEvent motionEvent) {
switch (motionEvent.getAction()) {
case MotionEvent.ACTION_DOWN:
handler.removeCallbacks(handlerRunnable);
handler.postDelayed(handlerRunnable, initialInterval);
touchedView = view;
touchedView.setPressed(true);
clickListener.onClick(view);
return true;
case MotionEvent.ACTION_UP:
case MotionEvent.ACTION_CANCEL:
handler.removeCallbacks(handlerRunnable);
touchedView.setPressed(false);
touchedView = null;
return true;
}
return false;
}
}
How about checking the visibility before increasing the counter
public boolean onTouch(View view, MotionEvent motionEvent) {
switch (motionEvent.getAction()) {
case MotionEvent.ACTION_DOWN:
if(view.getVisibility() == View.VISIBLE){
handler.removeCallbacks(handlerRunnable);
handler.postDelayed(handlerRunnable, initialInterval);
touchedView = view;
touchedView.setPressed(true);
clickListener.onClick(view);
}
return true;
case MotionEvent.ACTION_UP:
case MotionEvent.ACTION_CANCEL:
if(view.getVisibility() == View.VISIBLE){
handler.removeCallbacks(handlerRunnable);
touchedView.setPressed(false);
touchedView = null;
}
return true;
}
return false;
}
Try this line
button.setVisibility(View.GONE);
instead of
button.setVisibility(View.INVISIBLE);
Just set your listener to null when you reach a specific number and show imageview and make button invisible then after 5 seconds again set your listener and make button visible
I am having weird problems with Android GridView. I create a 3x4 grid and insert buttons into that grid. I want the background of the button to change when the user clicks that button. And this is working just fine for all buttons except the first one (the one with index 0 - top left). OnClick event listener doesn't fire at all for that button no matter what I do.
Here is the code where I create the view:
public View getView(int position, View convertView, ViewGroup parent) {
Button imageView;
if (convertView == null) { // if it's not recycled, initialize some attributes
Log.w("NOVO", "narejena nova celica");
imageView = new Button(mContext);
imageView.setPadding(8, 8, 8, 8);
} else {
Log.w("STARO", "stara celica");
imageView = (Button) convertView;
}
imageView.setEnabled(true);
int visina = parent.getHeight();
int sirina = parent.getWidth();
float dip = mContext.getResources().getDisplayMetrics().density;
float margin = 10*dip;
int view_height = (int)(visina - 3*margin)/4;
int view_width = (int)(sirina - 2*margin)/3;
int view_dim = 0;
if (view_height <= view_width)
view_dim = view_height;
else
view_dim = view_width;
imageView.setLayoutParams(new GridView.LayoutParams(view_dim, view_dim));
imageView.setId(position);
imageView.setOnClickListener(celice.get(position));
/*imageView.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
//Toast toast = Toast.makeText(mContext, v.getId() + "bla", Toast.LENGTH_SHORT);
//toast.show();
celice.get(v.getId()).celicaVisible(4000);
}});*/
celice.get(position).id = position;
celice.get(position).setButton(imageView);
return imageView;
}
If I replace
imageView = (Button) convertView;
with
imageView = new Button(mContext);
then the onClick() gets fired but the background still doesn't change. All the other buttons are working as expected.
And here is the custom class "Celica" that takes care of the actual work - changing the background...
public class Celica implements OnClickListener {
public boolean odkrit;
public boolean najden;
public int id;
public Drawable slikca1, slikca2;
public Celica par;
private Timer tim;
public Button but;
public Context con;
static int buttonsVisible = 0;
Celica(Drawable s1, Drawable s2) {
this.slikca1 = s1;
this.slikca2 = s2;
}
void celicaVisible(int millis) {
if (odkrit)
return;
Log.w("TEST", "prizganih " + buttonsVisible);
if (buttonsVisible >= 2)
return;
odkrit = true;
buttonsVisible++;
tim = new Timer();
tim.schedule(new timerDone(), millis);
((Activity)con).runOnUiThread(new Runnable() {
#Override
public void run() {
but.setBackground(slikca2);
}
});
}
void setButton(Button b) {
but = b;
((Activity)con).runOnUiThread(new Runnable() {
#Override
public void run() {
but.setBackground(slikca1);
}
});
}
class timerDone extends TimerTask {
#Override
public void run() {
if (!najden) {
odkrit = false;
((Activity)con).runOnUiThread(new Runnable() {
#Override
public void run() {
but.setBackground(slikca1);
}
});
}
buttonsVisible--;
tim.cancel();
}
}
#Override
public void onClick(View v) {
celicaVisible(4000);
}
}
In Android, ID of any View must be non zero and non negative number. means View ID should be > 0. and there is problem, when you are setting ID to the Button like
imageView.setId(position)
here ID of a button will be zero when position is zero(means first item). may be due to this, First Button's OnClickListener is not getting fired...try setting a ID that is greater than zero to Button and try once...
you can write like
imageView.setId(position+1) to ensure ID > 0
I actually figured it out. Everything works if I use the view that gets provided by the onClick() method instead of saving the actual button at the creation of the Celica object.
So basically adding:
but = (Button) v;
to the onClick() method solved the problem.
BELOW IS MY CODE. This code is working, but I want to get the value of the display image in array to test, if the display country is correct. Please help me . I'm stuck in this activity. Thanks for all help .
public class MainActivity extends Activity implements OnClickListener {
private boolean blocked = false;
private Handler handler = new Handler();
ViewFlipper flippy;
Button show;
TextView view;
int flags[] = { R.drawable.afghan, R.drawable.albania, R.drawable.algeria };
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.flipper);
flippy = (ViewFlipper) findViewById(R.id.viewFlipper1);
show = (Button) findViewById(R.id.button1);
view = (TextView) findViewById(R.id.textView1);
for (int i = 0; i < flags.length; i++) {
setflipperimage(flags[i]);
}
}
private void setflipperimage(int i) {
// TODO Auto-generated method stub
Log.i("Set Filpper Called", i + "");
ImageView image = new ImageView(getApplicationContext());
image.setBackgroundResource(i);
flippy.addView(image);
}
do not call this in loop,use this on click or on touch:
i+=1;
flippy.setDisplayedChild(flags[0]);
This will get used to get the current child id
viewFlipper.getDisplayedChild();
I'm trying to use an image gallery for my application menu. The objective is that when the user click on a image it will send you to a particular activity. The problem is that I donĀ“t know how to associate each image with each activity. For example if you click on the first image it opens a game, if you click on the second one you go to the application options... How can I do it?
public class Carrusel extends Activity implements OnClickListener {
ImageView lastClicked = null;
int padding = 10;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.start);
LinearLayout l;
l = (LinearLayout) findViewById(R.id.carrusel);
int[] images = new int[] { R.drawable.image1, R.drawable.image2,
R.drawable.image3,R.drawable.image4,R.drawable.image5};
for (int i = 0; i <5; i++) {
ImageView iv = new ImageView(this);
iv.setImageResource(images[i]);
iv.setPadding(padding, padding, padding, padding);
iv.setOnClickListener(this);
l.addView(iv);
}
}
#Override
public void onClick(View v) {
Intent i= new Intent (this, Flip3d.class);
startActivity (i);
}
}
The last "onClick" was a test of what I was trying. Obviously in this case all the images open the same activity, that is what I want to change.
Create on OnClickListener for each of your ImageViews.
iv.setOnClickListener (new OnClickListener() {
#Override
OnClick(View v) {
// start the activity you want
}
});
You can set ids for your imageview which can be used in onClick to identify your view.
protected void onCreate(Bundle savedInstanceState) {
// ...
for (int i = 0; i <5; i++) {
ImageView iv = new ImageView(this);
iv.setImageResource(images[i]);
iv.setPadding(padding, padding, padding, padding);
iv.setOnClickListener(this);
iv.setId(mIvIds[i]);
l.addView(iv);
}
}
public void onClick(View v) {
if (v.getId() == mIvIds[0]) {
Intent i= new Intent (this, Flip3d.class);
startActivity (i);
} else if (v.getId() == mIvIds[1]) {
// other stuff
} else if (v.getId() == mIvIds[2]) {
// ...
}
}
But firstly you need to generate new ids for mIvIds[]. In API17 was View.generateViewId() added for this feature. But if only your imageviews are attached to that onclick listener i think there should be no problem if you use some random integers (e.g. 1,2,3,... )
Am beginner to android..I developed an app like if i press prev and next button it will display prevous and next images....
But I had issue in my app..The problem here was, if app execute i set an current image source as IMAGE_IDS[0]... So that if i pressed left arrow app gets force close, actually if i press left arrow it shows last image in the array IMAGE_IDS... Any idea ??? Thank You !
public class MainActivity extends Activity implements OnClickListener{
ImageButton play;
ImageButton ib_left_arrow, ib_right_arrow;
ImageView slidingimage;
Animation rotateimage;
private int[] IMAGE_IDS = { R.drawable.image1, R.drawable.image2,
R.drawable.image3};
int imglength=IMAGE_IDS.length;
int img_position;
int img_minus;
int img_plus;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.movies);
ib_left_arrow = (ImageButton) findViewById(R.id.iv_left_arrow);
ib_right_arrow = (ImageButton) findViewById(R.id.iv_right_arrow);
ib_left_arrow.setOnClickListener(this);
ib_right_arrow.setOnClickListener(this);
slidingimage = (ImageView) findViewById(R.id.ImageView3_Left);
slidingimage.setImageResource(IMAGE_IDS[0]);
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
switch (v.getId()) {
case R.id.iv_left_arrow:
img_minus=--img_position;
slidingimage.setImageResource(IMAGE_IDS[img_minus% IMAGE_IDS.length]);
rotateimage = AnimationUtils.loadAnimation(this,R.anim.slide_in_left);
slidingimage.startAnimation(rotateimage);
break;
case R.id.iv_right_arrow:
img_plus=++img_position;
slidingimage.setImageResource(IMAGE_IDS[img_plus% IMAGE_IDS.length]);
rotateimage = AnimationUtils.loadAnimation(this,R.anim.slide_in_right);
slidingimage.startAnimation(rotateimage);
break;
}
}
}
I think the problem is img_plus% IMAGE_IDS.length when setting the image position in the array.
I would try:
#Override
protected void onCreate(Bundle savedInstanceState) {
img_position = 0;
imglength = IMAGE_IDS.length;
slidingimage.setImageResource(IMAGE_IDS[img_position]);
// ...
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
switch (v.getId()) {
case R.id.iv_left_arrow:
img_position--;
break;
case R.id.iv_right_arrow:
img_position++;
break;
}
// this is to check if your current position is out of array bounds, you could
// handle here your exit if you want to close the app when pressing left and
// img_position = 0 || img_position < 0
if(img_position < 0) img_position = imglength-1;
if(img_position >= imglength) img_position = imglength -1;
slidingimage.setImageResource(IMAGE_IDS[img_position]);
Its happening because of this line
img_minus=--img_position;
and this calculation
img_plus % IMAGE_IDS.length
If it's at 0 then
img_minus=--img_position;//img_minus = --0 therefore img_minus = -1
//img_plus % IMAGE_IDS.length // -1 % 3 = 2
slidingimage.setImageResource(IMAGE_IDS[2]);//which is the last image.
So if you want to close the Activity if left is pressed then
img_minus=--img_position;
if(img_minus < 0({
finish();
return;
}
imgposition=0;
case R.id.iv_left_arrow:
if(0<img_position){
--img_position;
slidingimage.setImageResource(IMAGE_IDS[img_position]);
rotateimage = AnimationUtils.loadAnimation(this,R.anim.slide_in_left);
slidingimage.startAnimation(rotateimage);}
break;
case R.id.iv_right_arrow:
if(2>=counter)
{
++img_position;
slidingimage.setImageResource(IMAGE_IDS[img_position]);
rotateimage = AnimationUtils.loadAnimation(this,R.anim.slide_in_right);
slidingimage.startAnimation(rotateimage);}
break;