0

I have been trying to change my ImageButton source OnClick and change it back after 500 miliseconds. This is the code (There are more ImageButtons, this is just the complete example of one of the ImageButtons): [UPDATED]

package com.example.apptest;

import android.app.Activity;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.widget.ImageButton;

public class MainActivity extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
        setContentView(R.layout.mainactivitylayout);

        ImageButton Next=(ImageButton)findViewById(R.id.nexticon);
        // Here there are more buttons //
        
        Next.setOnClickListener(new View.OnClickListener() {

            public void onClick(View view) {
            Intent splash = new Intent(MainActivity.this, NextActivity.class);
                startActivity(splash);
                overridePendingTransition(R.anim.fade_in, R.anim.fade_out);
                ImageButton.setImageResource(R.mipmap.imgbtnonclick);
                Handler h =new Handler();
                h.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        findViewById(R.id.nexticon);
                        ImageButton.setImageResource(R.mipmap.imgbtn);
                    }
                }, 500);
            }
        });
}
 

It doesn't work, the message grade build says:[UPDATED]

Error:(34, 28) error: non-static method setImageResource(int) cannot be referenced from a static context

Error:(40, 36) error: non-static method setImageResource(int) cannot be referenced from a static context

Hope you can help me. Thanks!

Community
  • 1
  • 1
Matej Varga
  • 95
  • 2
  • 14
  • My bad, it wasn't the logcat but the grade build message, didn't let me build the project and launch the emulator. – Matej Varga Aug 28 '15 at 08:25

4 Answers4

2

You're trying to assign a drawable to a resource property. use setBackground instead.

ImageButton.setBackground(getResources().getDrawable(R.mipmap.imgbtn));

Something else I see is that ImageButton is a class, that is why you get the error message about static context. You should have a reference of the button you want to change the image using view.findViewById()

You can use ButterKnife to easily bind buttons and apply methods to group of buttons.

Bind the buttons:

@Bind({R.id.nexticon, R.id.nexticon2, R.id.nexticon3, R.id.nexticon4}) List<View> allButtons;

Define the action:

static final ButterKnife.Action<View> changeImageSource = new ButterKnife.Action<View>() {
        @Override public void apply(View view, int index) {
             ImageButton.setImageResource(R.mipmap.imgbtnonclick);
                Handler h =new Handler();
                h.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        findViewById(R.id.nexticon);
                        ImageButton.setImageResource(R.mipmap.imgbtn);
                    }
                }, 500);
        }
    };

Execute the action:

Next.setOnClickListener(new View.OnClickListener() {

            public void onClick(View view) {
            Intent splash = new Intent(MainActivity.this, NextActivity.class);
                startActivity(splash);
                overridePendingTransition(R.anim.fade_in, R.anim.fade_out);
              ButterKnife.apply(allButtons, ADDLISTENER);
            }
        });

Still what you're trying to do I think is better using a background selector defined in xml and then change the state of the button temporarily. Here is an example:

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">

    <item android:drawable="@drawable/buttonok_pressed"
          android:state_enabled="false" />

    <item android:drawable="@drawable/buttonok" />

</selector>

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
       android:shape="rectangle"
       android:minWidth="@dimen/button_minwidth"
    >

    <corners android:radius="@dimen/button_radius"/>

    <gradient
    android:angle="45"
        android:centerX="35%"
        android:centerColor="#0070DC"
        android:startColor="#00A0E2"
        android:endColor="#0001CF"
        android:type="linear"
    />

    <padding
        android:left="@dimen/button_paddingH"
        android:top="@dimen/button_paddingV"
        android:right="@dimen/button_paddingH"
        android:bottom="@dimen/button_paddingV"
        />


    <stroke
        android:width="2dp"
        android:color="#0000FF"
    />

</shape>

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
       android:shape="rectangle"
       android:minWidth="@dimen/button_minwidth">

    <corners android:radius="@dimen/button_radius"/>

    <gradient
        android:angle="45"
        android:centerX="35%"
        android:centerColor="#0097FC"
        android:startColor="#00D5FF"
        android:endColor="#0011FF"
        android:type="linear"
    />

    <padding
        android:left="@dimen/button_paddingH"
        android:top="@dimen/button_paddingV"
        android:right="@dimen/button_paddingH"
        android:bottom="@dimen/button_paddingV"
    />

    <stroke
        android:width="2dp"
        android:color="#0000FF"
    />

</shape>

Also I suggest you to not go for fast results or just make it work and try different stuff around. I guess you're starting developing with Android and focus on learning and experimenting for now.

Origence
  • 155
  • 3
  • 10
  • Just changed that, I am still getting errors like: Expression expected, getDrawable(Int) is deprecated and non static method cannot be reference from a static context for (setbackground and postdelayed), should I change the class? There are many buttons on the screen and I had to use a list to include them all, so I don't really know where to include the code so it works. – Matej Varga Aug 28 '15 at 08:31
  • I added more information. I suggest you to read slowly, maybe even google more information about the topics like selector, ButterKnife, search tutorials, etc.. I see you're learning and at this stage is better to focus on learning than rushily make things work – Origence Aug 28 '15 at 09:36
  • Thank you for you code, but I just solved it with OnTouchListener. I started like 2 weeks ago. I had installed ButterKnife and haven't started using it yet, but I will give it a try after looking up some tutorials. I will choose your answer as my solution doesn't match with the content of this question. By the way, you seem very experienced, do you know of any way to change the motion speed for onTouchListener? Thank you! – Matej Varga Aug 28 '15 at 09:45
0

try like this

imageView.setImageResource(R.drawable.your_icon);

or

imageView.setImageDrawable(getResources().getDrawable(R.drawable.your_icon));

imageView.setBackground(..)

this will change background not src

slartidan
  • 20,403
  • 15
  • 83
  • 131
Rustam
  • 6,485
  • 1
  • 25
  • 25
  • imageView.setBackground(..) that works, but I am getting errors for misplaced semicolon, unexpected token and non static method referenced from a static context. – Matej Varga Aug 28 '15 at 08:38
0

The method you call, setBackgroundResource() expects you to give an Integer as argument. In this case, it refers to the R.mipmap.imgbtn value. instead of writing getResources().getDrawable(R.mipmap.imgbtn), just pass ImageButton.setBackgroundResource(R.mipmap.imgbtn).

Also you should move your imgbtn to the drawable folder instead of mipmap (which is used for launcher icons(Then the code would begetResources().getDrawable(R.drawable.imgbtn)`

Joakim
  • 3,224
  • 3
  • 29
  • 53
  • Thank you, I changed to setBackgroundResource. As for the mipmap, why is it convenient to change it to my drawable? I am keeping my xml extra files there for animations etc. I added a big bunch of pngs to that directory and it gave me error until I placed it in one of my mipmap directories. – Matej Varga Aug 28 '15 at 08:35
0

You are accessing Handler and ImageButton statically

Instead of:

 Handler=new Handler();
            Handler.postDelayed(new Runnable() {
                @Override
                public void run() {
                    ImageButton.setBackgroundResource(getResources().getDrawable(R.mipmap.imgbtn));
                }
            }, 500);

use:

Handler h =new Handler();
            h.postDelayed(new Runnable() {
                @Override
                public void run() {
          //Here ImageButton also should be initialized (findViewByd(R.id.yourImageButton)) 
          ((ImageButton) view.findViewById(R.id.yourImageView)).setBackgroundResource(getResources().getDrawable(R.mipmap.imgbtn));
                }
            }, 500);
hrskrs
  • 4,447
  • 5
  • 38
  • 52
  • Looks good, solved the Handler error, I am getting this error: Error:(34, 77) error: incompatible types: Drawable cannot be converted to int Error:(40, 85) error: incompatible types: Drawable cannot be converted to int and also setBackgroundResource static context issue. – Matej Varga Aug 28 '15 at 08:47
  • remove `getResources().getDrawable()`, use only `R.mipmap.imgbtn` with `setBackgroundResource` as it expects `Integer` and not a `Drawable` – hrskrs Aug 28 '15 at 08:50
  • Thanks, just tried that and I am still getting the static context error on both setBackgrounfResource. I do vote the helpful answers, it's not showing yet, because I am new to the site though. – Matej Varga Aug 28 '15 at 08:54
  • try changing `setBackgroundResource(getResources().getDrawable(R.mipmap.imgbtn));` to `setBackground(getResources().getDrawable(R.mipmap.imgbtn));` – hrskrs Aug 28 '15 at 08:54
  • Same, non static method referenced from static context. Could it be the place where the code is? As I mentioned before, I have like seven buttons I will be modifying and I successfully programmed them to call a new intent. I just wanted to style them as a hover effect and used the intent clicklisteners to do that. I really don't know what's failing now. – Matej Varga Aug 28 '15 at 08:58
  • @MatejVarga check every place if you are calling `ImageButton` statically – hrskrs Aug 28 '15 at 09:04
  • I am going to post the complete java code for one of the buttons as an example so you see how it's programmed. My ImageButton gets the image from src, background is android's transparent. – Matej Varga Aug 28 '15 at 09:07