I have a code with lots of imageview and I would like to dynamically change them on a click.
Do I really have to create a condition for every imageview clicked or can I do it simpler?
As an example, is there a way to do something like:
#override
public void onClick(View view) {
view.setImageBitmap(null)
}
You can do this if you haven't yet, give onClick for all the images that you put
<ImageView
android:id="#+id/image1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="#drawable/image_1"
android:onClick="onClick"
android:layout_weight="1"
android:layout_gravity="center_horizontal"
/>
Then in the activity you can make the Activity implement View.OnClickListener() and then define its onClick method as
#Override
public void onClick(View view) {
switch (view.getId()){
case R.id.image1:
//Do your thing
break;
case R.id.image2:
//Do your thing
break;
//Add all cases like this
}
}
Let me know if this was helpful to you.
In fact, I found a quite simple way to awnser my problem.
first, I put all imageviews in an array and get the id of these in another array.
Then I use Arrays.asList(array).indexOf(view.getId());
Pic[0] = (ImageView) findViewById(R.id.imageView1);
Pic[1] = (ImageView) findViewById(R.id.imageView2);
Pic[2] = (ImageView) findViewById(R.id.imageView3);
...
for (int i = 0; i < Pic.length; i++){
id[i] = Pic[i].getId()
}
int u = Array.asList(id).indexOf(view.getId())
Pic[u].Setimagebitmap(null)
Related
My Xml file:-
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#drawable/pagefw">
<ImageView
android:id="#+id/imageView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:layout_marginLeft="51dp"
android:layout_marginTop="140dp"
android:src="#drawable/cross" />
</RelativeLayout>
My activity class:-
int turn=1;
iv1 = (ImageView)findViewById(R.id.imageView1);
//iv1.setVisibility(View.INVISIBLE);
//iv1.setImageAlpha(0);
iv1.setOnClickListener(new View.OnClickListener()
{
public void onClick(View v)
{
// TODO Auto-generated method stub
Toast.makeText(getApplicationContext(),
"Image View 1 selected", Toast.LENGTH_SHORT).show();
if(turn%2!=0)
{iv1.setVisibility(View.INVISIBLE);}
else
{iv1.setVisibility(View.VISIBLE);}
turn++;
}
});
What I Did:-
I added an ImageView in the activity having an image, which has onClickListener assigned to it.
What I Want:-
To my image set in the imageview to completely become invisible and visible after each click, i.e. after first click it becomes invisbile and after another click visible and so on.
What I Get:-
After first becoming invisible the image never becomes visible nor am I getting the toast when I click the invisible imageView. I also tried doing it with iv1.setAlpha(); method but also with no result.
Try something like this , using this u'll not need any extra variable
if(iv1.getVisibility()==View.INVISIBLE){
iv1.setVisibility(View.VISIBLE);
}else{
iv1.setVisibility(View.INVISIBLE);
}
Edit:
I have tried and worked using a Button or removing background.
You are applying click on same ImageView, thats the reason why not working for u.You should apply onClick on a diff button. If want on same ImageView than u have to remove Background instead making it invisible.as ex, u have several method to remove bg/src which u can use.one of them
iv1.setBackgroundResource(null);
Edit-2
Ur imageview must have a min height and width as after removing bg ,imageview clicking area is very small.
<ImageView
android:id="#+id/iv1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#drawable/ic_launcher"
android:minHeight="48dp"
android:minWidth="48dp"
android:onClick="onClick" />
and a boolean for handle image during onClick
boolean avail=false;
and onClick code.
if (avail) {
iv1.setBackgroundResource(0);
avail = false;
} else {
iv1.setBackgroundResource(R.drawable.ic_launcher);
avail = true;
}
Make it more simple by using one boolean paramater that hold the button state, either pressed or not as following:
static final boolean isPressed= false;
iv1 = (ImageView)findViewById(R.id.imageView1);
iv1.setOnClickListener(new View.OnClickListener()
{
public void onClick(View v)
{
// TODO Auto-generated method stub
Toast.makeText(getApplicationContext(),
"Image View 1 selected", Toast.LENGTH_SHORT).show();
if(!isPressed){
isPressed= true;
iv1.setVisibility(View.INVISIBLE);
} else {
isPressed= false;
iv1.setVisibility(View.VISIBLE);
}
}
});
Set the tag on the image. Set tag 1 or 0 and check the tag to change the visibility of the image.
if(v.getTag()==0)
{
iv1.setVisibility(View.INVISIBLE);
v.setTag() == 1;
}
else
{
iv1.setVisibility(View.VISIBLE);
v.setTag() == 0;
}
I suggest you do it this way:
in your xml you provide the actual width and height of a drawable and do not provide source:
<ImageView
android:id="#+id/imageView1"
android:layout_width="_some_value_"
android:layout_height="_some_value_"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:layout_marginLeft="51dp"
android:layout_marginTop="140dp">
</ImageView>
That is for your view not to become of a size 0*0 when you set your background to something like null or transparent or whatever.
Then, in your activity:
protected void onCreate(Bundle savedInstanceState) {
.....
iv1.setBackgroundResource(R.drawable.cross);
...
}
And onClick():
public void onClick(View v)
{
Toast.makeText(getApplicationContext(),
"Image View 1 selected", Toast.LENGTH_SHORT).show();
if(turn%2!=0)
{iv1.setBackgroundResource(Color.TRANSPARENT);}
else
{iv1.setBackgroundResource(R.drawable.cross);}
turn++;
}
Pretty sure you can simply it like this too:
iv1.setVisibility(!iv1.getVisibility());
Know what I mean?
if(iv1.getVisibility()==View.INVISIBLE){
iv1.setVisibility(View.VISIBLE);
}else{
iv1.setVisibility(View.INVISIBLE);
}
Inside my Activity I start a simple dialog.
final Dialog myDialog = new Dialog(this);
myDialog.setContentView(R.layout.testing);
...
My testing.xml Layout consists of nothing but 10 ImageViews, id`s are '1' to '10'.
I want every ImageView to be clickable and to do something.
The define the onclick() methode in the .xml file isn`t working, as the methode can't be found when the dialog is viewed.
The only way I got it work is following: define 10 onclick-listeners:
ImageView img_1 = (ImageView) myDialog.findViewById(R.id.1);
ImageView img_2 = (ImageView) myDialog.findViewById(R.id.2);
...
img_1.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View view) {
execute_funtion(1);
myDialog.cancel();
}
});
img_2.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View view) {
execute_funtion(2);
myDialog.cancel();
}
});
...
However, that's really bad code, I have 10 times nearly the same lines.
So my question: How can I make that work with clean code?
I thought about a multiple onclicklistener (overwride the onClick() function and make a switch/case in the functions or something like that), but it's not working.
I'm happy about every idea!
Thanks
/EDIT
Here a snippet of the .xml file
<ImageView
android:id="#+id/1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="2dp"
android:onClick="myFunction"
android:src="#drawable/ic_launcher" />
Make your Activity implement OnClickListener and then process the onClick event like below:
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.img1:
...
break;
case R.id.img2:
...
break;
}
}
You should let your Activity/Fragment implement the OnClickListener.
When you do that you will have to override the onClick method in that particular activity/fragment.
Set the onClickListeners on the images as follows:
img_1.setOnClickListener(YourActivity.this);
Then in that onClick method you can put a switch case or an if else if case as follows
#Override
public void onClick(View v)
{
if(v==img_1) {
//do this
} else if(v==img_2) {
//do that
}...
}
or
#Override
public void onClick(View v)
{
switch (v.getId()) {
case img_1.getId(): // do this
break;
case img_2.getId(): // do that
break;
.
.
.
default : break;
}
}
I have a serie of ImageViews on my Activity. And I wanna execute a method when one of these is touched. I have the next:
public void onClick(View v) {
switch(v.getId()){
case R.id.image1:
mymethod(1,1,movimientos,(ImageView)v);
break;
case R.id.image2:
ponerficha(1,2,movimientos,(ImageView)v);
break;
case R.id.image3:
...
But the method isn't executed, The problem not is the method, because any code in the cases not work. Any idea?
First thing what you need to check if you already register onClickListener for your Images
image.setOnClickListener(this);
(This you have to use if your class implements OnClickListener interface)
Then how you declare and initialize your ImageViews, whether have own ids.
image = (ImageView) findViewById(R.id.someId)
anotherImage = (ImageView) findViewById(R.id.anotherId)
...
You can work with onClickListeners like with anonyme classes like
image.setOnClickListener(
new View.OnClickListener() {
public void onClick(View v) {
// some actions
}
});
but more complex and better in the case you have many widgets to set implement OnClickListener.
public class ClassName extends Activity implements View.OnClickListener {}
First, your activity has to implement View.OnClickListener like so
public class myActivity implements View.OnClickListener {
Then you need to set your on click listener for your ImageViews. If all your ImageViews are in a linearlayout then the code would look like this
LinearLayout llImageViewHolder = (LinearLayout) findViewById(R.id.llImageViewHolder);
for (int i = 0; i < llImageViewHolder.getChildCount(); i++ {
ImageView iv = (ImageView) llImageViewHolder.getChildAt(i);
iv.setOnClickListener(this);
}
Cheers.
You need to add an onClick handler to each view you are interested in processing clicks for.
How you do it depends on how you want to process the click events. You can either use hawaii.five-0's approach and have one event handler for everything, or you can have one event handler per view item which you could add in the onCreate method of your activity:
ImageView imageView = (ImageView) findViewById(R.id.image_view);
imageView.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View v)
{
// Do something
}
}
In my project, there are a number of images having back and forward images and all images having a common layout. On clicking back and next buttons new images should be displayed.
private int imageCounter = 0;
private ImageView imageView;
private int[] imageArray = {R.drawable.image_w_lbl_0, R.drawable.image_w_lbl_1,};
private int index_count = 0;
#Override
public void onCreate(Bundle savedInstanceState)
{
setContentView(R.layout.frame0);//this one is the common parent layout for all imageviews
super.onCreate(savedInstanceState);
imageView = new ImageView(this);
ImageButton next = (ImageButton) findViewById(R.id.next);
ImageButton back = (ImageButton) findViewById(R.id.back);
next.setOnClickListener(this);
back.setOnClickListener(this);
//show the default image
this.loadImage(imageArray[0]);
}
#Override
public void onClick(View v)
{
int imagePath = 0;
// TODO Auto-generated method stub
switch (v.getId())
{
case R.id.next:
if(imageCounter < 25)
{
imagePath = imageArray[index_count];
}
imageCounter++;
break;
case R.id.back:
if(imageCounter > 0)
{
//imagePath =
}
imageCounter--;
break;
}
this.loadImage(imagePath);
}
private void loadImage(int imagePath)
{
imageView.setImageResource(imagePath);
}
I am able to see my layout only in the output having back and forward buttons with the black background not an image from my drawable folder.
XML Layout:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:gravity="center">
<ImageButton android:id="#+id/back" android:src="#drawable/btn_back"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="left"/>
<ImageButton
android:id="#+id/next"
android:src="#drawable/btn_next"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="right" />
</LinearLayout>
int array of images from resources (i.e. res/drawable-mdpi):
Integer[] imageArray = { "R.drawable.img1", "R.drawable.img2" }
...
imageView.setImageResource(imageArray[0]); // displays img1
Not very clear what you are asking, but do you want to do something like this:
imagePath=R.drawable.image_wo_lbl_0;
You can store image path in this way, if you actually want to do this.
imageView.setImageResource(R.drawable.img1)
Easiest way - Can be consider the below code
We can take advantage of Imageview setImageResource , refer below code for the same.
put image in the drawable like the below order
image_1.png, image_2.png, etc.
int imagePosition = 1;
int resId = getResources().getIdentifier("image_" + imagePosition, "drawable", getPackageName());
imageview.setImageResource(resId);
Use ContextCompat to get drawable(Image in your case). This is one of the new ways to set image to your image view.
imageView.setImageDrawable(ContextCompat.getDrawable(getApplicationContext(),
R.drawable.your_image));
You can use ContextCompat to get colors as well.
I use it in my apps and it works properly.
The onClick never fires! Why not? Please help me.
for(int i = 0; i < 12; i++) {
String title = "Button" + i;
Button sliderButton = new Button(this);
sliderButton.setText(title);
glideMenuTray.addView(sliderButton,100,40);
sliderButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Log.d("gm", "Tapped ");
}
});
}
I'm no expert at stuff like this, but it's probably something to do with garbage collection, and the OnClickListeners passing out of scope.
Though I don't think you can use the super-easy approach to onClickListeners that Dimitar mentions, you can probably use the middle approach that the section he links to discusses, even though it's not a new approach. To repeat the example code here, it's:
View.OnClickListener handler = View.OnClickListener() {
public void onClick(View v) {
switch (v.getId()) {
case R.id.myButton: // doStuff
break;
case R.id.myOtherButton: // doStuff
break;
}
}
}
findViewById(R.id.myButton).setOnClickListener(handler);
findViewById(R.id.myOtherButton).setOnClickListener(handler);
If the only thing distinguishing the buttons is their title text, well, you could use that to distinguish between them in the master onClick method.
Also, not shure, I once had a problem like that on a TextView and it was because I didnt add setClickable(true)
My code was something like
TextView text = new TextView(this);
text.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
text.setText("***");
text.setClickable(true);
text.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//My action
}
});
myViewGroup.addView(text );
Hope this helps
If you are using Donut or Eclair, you can use common click listener, registered in your Activity and hooked with your buttons in the layout XML.
For reference, look here, the category Easier click listeners.
Am I right in assuming that the following line:
glideMenuTray.addView(sliderButton,100,40);
Adds the view to the coords x:100,y:40 onto some View extending ViewGroup?
In that case you are stacking 12 buttons on top of each other, only the last Button (labeled Button11) will be visible (and clickable).
And provided that the question is 3 years old I really hope you already resolved this by now :)
set the setOnClickListener before adding the view.
for(int i = 0; i < 12; i++) {
String title = "Button" + i;
Button sliderButton = new Button(this);
sliderButton.setText(title);
sliderButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Log.d("gm", "Tapped ");
}
glideMenuTray.addView(sliderButton,100,40);
}