android之实现各个组件点击事件监听
布局:layout/activity_main.xml
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
android:text="点击变字体颜色"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:clickable="true"
/>
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@drawable/ic_launcher"
/>
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
android:text="男"
android:checked="true"
/>
android:text="女"/>
android:text="变男"/>
android:text="变女"/>
java类:
package com.example.day03_01;
import android.support.v7.app.ActionBarActivity;
import android.graphics.Color;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.CheckBox;
import android.widget.ImageView;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.RadioGroup.OnCheckedChangeListener;
import android.widget.TextView;
public class MainActivity extends ActionBarActivity {
private RadioButton rbMale ;//初始化-----男
private RadioButton rbfaMale ;//初始化------女
private RadioGroup rg;
private TextView tv;
private ImageView iv;
private CheckBox cbMale;
private CheckBox cbfaMale;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
init();
setListener();
}
private void setListener() {
// TODO Auto-generated method stub
cbMale.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View view) {
// TODO Auto-generated method stub
rbMale.setChecked(((CheckBox)view).isChecked());
rbfaMale.setChecked(!((CheckBox)view).isChecked());
}
});
cbfaMale.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View view) {
rbMale.setChecked(!((CheckBox)view).isChecked());
rbfaMale.setChecked(((CheckBox)view).isChecked());
}
});
tv.setOnClickListener(new OnClickListener(){
@Override
public void onClick(View view) {
// TODO Auto-generated method stub
TextView tv = (TextView)view;
tv.setTextColor(Color.RED);
}
});
iv.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View view) {
// TODO Auto-generated method stub
ImageView iv = (ImageView)view;
iv.setImageResource(R.drawable.p01);
}
});
}
private void init(){//初始化 ----男,女
rbMale = (RadioButton) findViewById(R.id.rbMale);
rbfaMale = (RadioButton) findViewById(R.id.rbfaMale);
rg = (RadioGroup)findViewById(R.id.rg);
tv = (TextView)findViewById(R.id.tv);
iv = (ImageView)findViewById(R.id.iv);
cbMale = (CheckBox)findViewById(R.id.cbMale);
cbfaMale = (CheckBox)findViewById(R.id.cbfaMale);
}
}
效果: