天天看点

android+3.1.2+imagebutton监听,button以及Imagebutton的使用

1.XML文件中初始化

android:id="@+id/button1"

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:layout_alignLeft="@id/EditText1"

android:layout_below="@id/EditText1"

android:layout_marginTop="17dp"

android:text="一按就知道" />

android:id="@+id/ImageButton1"

android:layout_below="@id/button1"

android:layout_marginTop="17dp"

android:layout_width="wrap_content"

android:layout_height="wrap_content"

/>

2.java文件中

final Button button = (Button)findViewById(R.id.button1);

button.setBackgroundColor(Color.rgb(0, 0, 255));

ImageButton imagebutton = (ImageButton)findViewById(R.id.ImageButton1);

imagebutton.setImageResource(R.drawable.aaa);

button.setOnClickListener(new View.OnClickListener() {

@Override

public void onClick(View v) {

// TODO Auto-generated method stub

button.setText("你按啦!");

button.setBackgroundColor(Color.rgb(255,112,112));

}

}); //写在oncreate里面

注意:

(1)添加的监听器依然写在oncreate函数中

(2)button前面使用final关键字修饰,否则出错。

在使用Java局部内部类或者匿名内部类时,若该类调用了所在方法的局部变量,则该局部变量必须使用final关键字来修饰,否则将会出现编译错误“Cannot refer to a non-final variable * inside an inner class defined in a different method”

final关键字:修饰类,表示这个类不能被继承;

修饰方法,将方法锁定,以防任何继承类修改它的含义;

修饰变量,如果是基本数据类型的变量,值初始化后就不能修改,如果是引用类型变量,初始化后不能指向其他对象。

3.两个按钮注册到一个监听器上

@Override

public void onClick(View v){

switch(v.getId()){

case R.id.button1:

button.setText("哈哈,你按我啦!");

editText1.setText("button");

return;

case R.id.ImageButton1:

button.setText("你按我呀~");

editText1.setText("imagebutton");

return;

}

}

};

button.setOnClickListener(buttonListener);

imagebutton.setOnClickListener(buttonListener);

注意:最后两句为将该监听器分别注册到两个按钮上。

初始化

android+3.1.2+imagebutton监听,button以及Imagebutton的使用

点击button

android+3.1.2+imagebutton监听,button以及Imagebutton的使用

点击imagebutton

android+3.1.2+imagebutton监听,button以及Imagebutton的使用