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);