Search code examples
androidbuttonandroid-activityprogram-entry-pointdemo

Accessed from within inner Class


I am very new to Android programming and have a little problem.

The Error is:

Variable 'Demo_Button' is accessed from within inner class. Needs to declared final.

What i tried:

changed Demo_button.setImageResource(R.drawable.pressed); to final Demo_button.setImageResource(R.drawable.pressed);

package com.iklikla.eightgame;

import android.os.Bundle;
import android.app.Activity;
import android.view.View;
import android.widget.ImageButton;

public class MainActivity extends Activity {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    ImageButton Demo_button = (ImageButton)findViewById(R.id.imageButton);

    Demo_button.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            Demo_button.setImageResource(R.drawable.pressed);
        }
    });
}

}

Solution

  • A couple options here

    First, I would declare it as a member variable then it will work

    public class MainActivity extends Activity {
    
        ImageButton Demo_button;
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
    
            Demo_button = (ImageButton)findViewById(R.id.imageButton);
    

    Second, since you are changing the View being clicked you can access it that way

    emo_button.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
    
        ImageButton btn = (ImageButton)v; // cast the View to an ImageButton
            btn.setImageResource(R.drawable.pressed);
        }
    });
    

    Not related but will give you an error at runtime with the current code, you need to inflate a layout before trying to initialize that Button (most likely with setContentView()). So using my first example it would look something like

    public class MainActivity extends Activity {
    
        ImageButton Demo_button;
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
           super.onCreate(savedInstanceState);
           setContentView(R.layout.my_layout);  // where my_layout is the name of your layout
                                                 // file containing the Button without the xml extension
           Demo_button = (ImageButton)findViewById(R.id.imageButton);