Changing src for ImageButton when clicked - android

I am doing an Android application in which I have placed an image button. I have given a default image source. When I click the image it should change the image source to another and if I press the image again I should get the default image back.
It's like toggling between two images. But I don't want to use toggleButton due to requirements of my app.

If you don't want anything to do with toggle, you would have to keep a counter.
XML:
<android.support.v7.widget.AppCompatImageButton
android:id="#+id/button"
android:layout_width="10dp"
android:layout_height="match_parent"
android:src="#mipmap/original"
android:background="#color/original"/>
Activity:
public class Activity extends AppCompatActivity {
int clickcounter = 0;
#Bind(R.id.button)
ImageButton Button;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//Butter Knife
ButterKnife.bind(this);
//Hook up the OnClick Listener
feedButton.setOnClickListener(feedButtonHandler);
}
View.OnClickListener feedButtonHandler = new View.OnClickListener() {
public void onClick(View v) {
clickcounter = clickcounter + 1;
if (clickcounter % 2 == 1) {
// setImageResource is the method for setting imagebutton's src in xml
Button.setImageResource(R.mipmap.new);
// setBackgroundResource is the method for setting imagebutton's background in xml
Button.setBackgroundResource(R.color.new);
}
if (clickcounter % 2 == 0) {
Button.setImageResource(R.mipmap.original);
Button.setBackgroundResource(R.color.original);
}
};
}
But toggle is a simpler way to do it.

ImageButton:
<ImageButton
android:id="#+id/imagebutton"
android:layout_width="250dp"
android:layout_height="100dp"
android:background="#drawable/img_btn_selector"/>
img_btn_selector:
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_selected="true" android:drawable="#drawable/img_selected" />
<item android:drawable="#drawable/img_un_selected" />
</selector>
Activity:
imgBtn.setOnClickListener(new OnClickListener() {
public void onClick(View button) {
if (button.isSelected()){
button.setSelected(false);
} else {
button.setSelected(true);
}
}
});

Related

Setting to events On Image View

I have created ImageView and i want to make two action on it :
First : when i press on the ImageView it chnages its Background, to do that, i created Drawable Resource File named imgpressed.xml and added attribute android:background="imgpressed in ImageView Layout
Second : If I click on it (Action UP) , Toast should appear on the screen, to do that , I created method SetOnClickListener in Java Code
but noticed that when i add attribute android:clickable in imageView , the OnClickListener in code java does not work, and if I remove the Attribute OnClickListener in Java Code works....
that is my codes :
imageView Layout :
<ImageView
android:clickable="true"
android:background="#drawable/imgpressed"
android:layout_width="100dp"
android:layout_height="100dp"
android:id="#+id/imageView"
android:contentDescription="#string/pauseimgS"
android:focusableInTouchMode="false"
android:background="#drawable/pauseimg"
android:layout_centerVertical="true"
android:layout_centerHorizontal="true"
/>
imgpressed.xml :
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_pressed="false">
<bitmap android:src="#drawable/pauseimg"/>
</item>
<item android:state_pressed="true">
<bitmap android:src="#drawable/pauseimgclicked"/>
</item>
</selector>
Code Java Main Activity
public class game extends AppCompatActivity {
RelativeLayout Rel_main_game;
View pauseButton;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.game);
LayoutInflater myInflater = (LayoutInflater) getApplicationContext().getSystemService(getApplicationContext().LAYOUT_INFLATER_SERVICE);
pauseButton = myInflater.inflate(R.layout.pause, null, false);
Rel_main_game = (RelativeLayout) findViewById(R.id.relativeLayout);
Rel_main_game.addView(pauseButton);
pauseButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(game.this,"Thank You", Toast.LENGTH_SHORT).show();
}
});
}
}
why you have used two backgrounds for your ImageView?!
you should use android:src="pauseimg" for your image source
and android:background="#drawable/imgpressed" for your background change
also for making your imageview clickable you can use android:onClick="onImageClick" and then in your activity:
public void onImageClick(View view) {
Toast.makeText(game.this,"Thank You", Toast.LENGTH_SHORT).show();
}

How to add icon image button in android studio

I want to design the layout of this type of app(as shown in the image). In this layout when we click the circle icon it moves to next page. I want to know how its done.
in drawer folder create circle_background.xml and put this code to it :
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="oval">
<solid android:color="#FE4543"></solid>
<stroke android:color="#FE4543" android:width="1dp"></stroke>
</shape>
so now in your activity add image view like this
<ImageView
android:layout_width="wrap_content"
android:gravity="center"
android:layout_height="wrap_content"
android:src="#drawable/ic_action_search"
android:padding="15dp"
android:id="#+id/btn_search"
android:background="#drawable/circle_background"
/>
and if you want to add click action on this you have to use intent something like this , my view id is btn_search so at the first i have to find it like this and then set onclick listener for it like below
ImageView btnSearch= (ImageView) findViewById(R.id.btn_search);
btnSearch.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent= new Intent(getApplicationContext(),ExampleActivity.class)
}
});
The top one I think it can implement by ImageButton simplely.
Another one need a Layout with a circle background, and contain ImageView and TextView.
Hope it will be help for you.
public class TourActivity extends AppCompatActivity {
private ImageView tour;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_tour);
tour = (ImageView) findViewById(R.id.tour);
tour.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent= new Intent(getApplicationContext(),FirstActivity.class);
launchThird();
}
});
}
private void launchThird() {
Intent intent = new Intent(this, FirstActivity.class);
startActivity(intent);
}
}

how to change the image on click of imagebutton?

I am make a image button .I need to change the image when I click on image button .Actually it change the background image but only for few seconds .why ?
here is my code
<ImageButton android:id="#+id/favorite"
android:layout_width="wrap_content"
android:layout_height="fill_parent"
android:src="#drawable/start"
android:background="#00ffffff"
/>
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_pressed="true"
android:drawable="#drawable/on" /> <!-- pressed -->
<item android:drawable="#drawable/off" /> <!-- default -->
</selector>
I need to show on image when I click on image button ..? can I write on java side ? can I write on click listener of image button ?
That's why you are using a selector for your button background and the image changes depending on the state of the button. If it is pressed the image will be "on" and in its normal state (no pressed and no focused) the image will be "off".
EDIT:
public class MainActivity extends AppCompatActivity {
ImageButton btn;
boolean isPressed;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btn = (ImageButton) findViewById(R.id.btn);
btn.setBackgroundResource(R.drawable.normal);
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(isPressed){
v.setBackgroundResource(R.drawable.normal);
}else{
v.setBackgroundResource(R.drawable.pressed);
}
isPressed = !isPressed; // reverse
}
});
}
<ImageButton
android:id="#+id/btn"
android:text="#string/hello_world" android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
Actually it change the background image but only for few seconds .why ?
I think it's obvious,those items in drawable are for states that ImageButton is pressed by user or in normal mode.
can I write on java side ? can I write on click listener of image button ?
Yes, and yes again :D if you want to change it when user presses it, just do it like this :
XML layout:
<ImageButton android:id="#+id/favorite"
android:layout_width="wrap_content"
android:layout_height="fill_parent"
android:src="#drawable/off"
android:background="#00ffffff"
/>
Java side (eg. in you onCreate method)
ImageButton favorite;
boolean isFav = false;
public void onCreate(Bundle savedInstanceState){
///...
favorite = findViewById(R.id.favorite);
favorite.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
isFav = !isFav;
if (isFav){
favorite.setImageResource(R.drawable.on);
}
else{
favorite.setImageResource(R.drawable.off);
}
}
});
///...
}
change the source of the image by providing an absolute path or an internet url dynamically in the onClickListener of the image.
image.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
//Here before changing the image you can check if the appropriate //image is set to the view.
image.setImageResource(R.drawable.on);
}
});
and also can be like this
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(isPressed){
v.setBackgroundResource(R.drawable.normal);
}else{
v.setBackgroundResource(R.drawable.pressed);
}
isPressed = !isPressed; // reverse
}
});

Android ImageButton - How to change the image when button is clicked?

If the button was clicked I want to turn on the wifi and also change the Image of ImageButton, but I do not know how to change it
I have also tried this from how to change the image of a button with every click? but is isn't working:
boolean isPressed=false
button.setOnClickListener(buttonListener);
OnClickListener buttonListener= new OnClickListener() {
#Override
public void onClick(View v) {
if(isPressed){
button.setBackgroundResource(R.drawable.icon1);
}else{
button.setBackgroundResource(R.drawable.icon2);
}
isPressed=!isPressed;
}};
when I write the code above, android studio shows this:
Cannot resolve symbol setOnClickListener
I have also created a button_wifi_selector xml, which it looks like this:
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<item android:drawable="#drawable/wifi_on"
android:state_pressed="true" />
<item android:drawable="#drawable/ic_launcher"
android:state_focused="true" />
<item android:drawable="#drawable/wifi" />
</selector>
and in my activity i have this
<ImageButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/imageButton_wifi"
android:layout_below="#+id/toggleButton_wifi"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:onClick="turnOffWifiDemo"
android:src="#drawable/button_wifi_selector" />
but it isn't doing, what I want
Can somebody pls help me?
Thanks
EDIT: it works with the first code. I just had to remove the onClick from ImageButton in the xml
BUT: he is changing the picture the second time, when I start the app. After that he changes it every time
this code work for me; test it
final ImageButton btnTest =(ImageButton) findViewById(R.id.btnexctract);
btnTest.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
btnTest.setSelected(!btnextra.isPressed());
if (btnTest.isPressed()) {
btnextra.setImageResource(R.drawable.yourImage);
}
else {
btnTest.setImageResource(R.drawable.yourImage2);
}
}
});
This is how you have to do it
Selector xml:
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item
android:state_selected="true"
android:drawable="#drawable/info_icon_solid_with_shadow" />
<item
android:drawable="#drawable/info_icon_outline_with_shadow" />
</selector>
And then in java:
//assign the image in code (or you can do this in your layout xml)
imageButton.setImageDrawable(getBaseContext().getResources().getDrawable(R.drawable....));
//set the click listener
imageButton.setOnClickListener(new OnClickListener() {
public void onClick(View button) {
//Set the button's appearance
button.setSelected(!button.isSelected());
if (button.isSelected()) {
//Handle selected state change
}
else {
//Handle de-select state change
}
}
});
I have modified it,for on/off it may help you
<FrameLayout
android:layout_width="match_parent"
android:layout_height="wrap_content" >
<ImageButton
android:id="#+id/imageButton_wifi2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="clickEvent"
android:visibility="invisible"
android:src="#drawable/on" />
<ImageButton
android:id="#+id/imageButton_wifi1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="clickEvent"
android:src="#drawable/off" />
</FrameLayout>
like you need to create method with view parameter
{
c=false;
im1=(ImageButton)findViewById(R.id.imageButton_wifi1);
im2=(ImageButton)findViewById(R.id.imageButton_wifi2);
}
public void clickEvent(View v)
{
//Code to implement
if(c) {
im2.setVisibility(View.VISIBLE);
im1.setVisibility(View.INVISIBLE);
c=false;
}
else {
im1.setVisibility(View.VISIBLE);
im2.setVisibility(View.INVISIBLE);
c=true;
}
You can use togglebutton like this
<ToggleButton
android:id="#+id/toggleButton1"
android:layout_width="74dp"
android:layout_height="26dp"
android:background="#drawable/toggle"
android:checked="false"
android:paddingRight="10dp"
android:text="ON"
android:textColor="#ffffff"
android:textSize="13sp"
android:textStyle="bold" />
And in java file
final ToggleButton toggleButton=(ToggleButton)findViewById(R.id.toggleButton1);
toggleButton.setOnCheckedChangeListener(new OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
// TODO Auto-generated method stub
if(isChecked){
//
toggleButton.setBackgroundResource(R.drawable.icon1);
}else{
//
toggleButton.setBackgroundResource(R.drawable.icon2);
}
}
});
You can define a boolean flag and just change visibility of items.
Description: changeBack is a button. This code is for change images
Your onClick does not know which id is clicked?
private boolean bgcolor = false;
public void onClick(View view) {
switch(view.getId())
{
case R.id.changeBack:
bgcolor = !bgcolor;
if (bgcolor) {
imv.setVisibility(View.VISIBLE);
imv2.setVisibility(View.INVISIBLE);
}
else {
imv2.setVisibility(View.VISIBLE);
imv.setVisibility(View.INVISIBLE);
}
break;
}
}

How do I switch the state of an imagebutton with a different image, once the button is selected

I have a java file which has the reference to the button:
public View onCreateView(final LayoutInflater inflater, final ViewGroup container, final Bundle savedInstanceState) {
createMenus();
return inflater.inflate(R.layout.fragment_test, container, false);
}
#Override
public void onClick(final View view) {
final int actionBarHeight = getActivity().findViewById(R.id.title_main_container).getHeight();
switch (view.getId()) {
case R.id.news_article_menu_button:
mOptionsMenuHelper.showMenu(view.getBottom() + actionBarHeight, Gravity.RIGHT);
break;
case R.id.text_size:
mTextSize = TextSize.values()[(mTextSize.ordinal() + 1) % TextSize.values().length];
updateFontSize();
break;
default:
throw new IllegalArgumentException("Invalid view Id" + view.getId());
}
}
private void setOnclickListeners(final View view){
final ImageButton button = (ImageButton) view.findViewById(R.id.menu_button);
button.setOnClickListener(this);
}
private void createMenus() {
mPreferenceMenuItems.add(PreferenceMenuItems.MENU_PREFERENCES);
mPreferencesMenuHelper = new MenuHelper(getActivity(), mPreferenceMenuItems,this);
mDeleteMenuItems.add(DeleteMenuItems.DELETE_PREFERENCES);
mDeleteMenuHelper = new MenuHelper(getActivity(), mDeleteMenuItems,this);
}
This is the corresponding button "over_btn" where the selector is defined:
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item
android:state_enabled="false"
android:drawable="#drawable/over_pressed" />
<item
android:state_pressed="true"
android:state_enabled="true"
android:drawable="#drawable/over_pressed" />
<item
android:state_focused="true"
android:state_enabled="true"
android:drawable="#drawable/over_pressed" />
<item
android:state_enabled="true"
android:drawable="#drawable/over" />
</selector>
and this is one of the corresponding xml files using the same fragment_test:
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="40dp"
android:layout_alignParentTop="true"
android:clickable="true"
android:background="#color/background_bar" >
<ImageButton
android:id="#+id/menu_button"
android:layout_width="49dp"
android:layout_height="48.5dp"
android:layout_alignParentRight="true"
android:layout_centerVertical="true"
android:background="#android:color/transparent"
android:gravity="right"
android:paddingRight="14dp"
android:src="#drawable/over_btn" />
</RelativeLayout>
I want the button to switch to a different image onclick and stay in that state till pressed again instead of highlighting once when pressed, is there any way to go about this?
Thanks!
Justin
add
<item
android:state_selected="true"
android:drawable="#drawable/info_selected" />
to your selector and when you click on the ImageButton, call view.setSelected(!view.isSelected()) to switch between status selected and unselected
public void onClick(final View view) {
switch (view.getId()) {
case R.id.imageButtonId:
view.setSelected(!view.isSelected());
break;
}
}
You should be able to do this with an onClick listener as show in this post.
//these are instance variables
private ImageButton button = null;
private boolean imageSwitched = false;
//call this method in your onActivityCreated() method. If the
//layout containing the button is not yet inflated you will not
//be able to find your image button.
private void initializeButton(){
button= (ImageButton)getActivity().findViewById(R.id.imgButton);
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
if(!imageSwitched){
button.setBackgroundResource(R.drawable.a);
imageSwitched = true;
} else {
buttons.setBackgroundResource(R.drawable.b);
imageSwitched = false;
}
}
});
}
To switch beteen 2 views you will need to use some state variable. I chose a boolean thats set on click to handle which image is swiched to on click.
Also if you don't want to use a listener you can set your button to have an onClick method in XML and use the same state handling idea
public void buttonSwitch(View v){
//state handling here
}
This way the method is called only when click and does not use the overhead of a listener.

Categories

Resources