android之实现各个组件点击事件处理:
注意:(TextView这个组件要点击产生效果的话,要设置,android:clickable="true"这个属性)
布局:layout/activity_main.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<TextView
android:id="@+id/tv"
android:text="点击变字体颜色"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:onClick="onClick"
android:clickable="true"
/>
<ImageView
android:id="@+id/iv"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@drawable/ic_launcher"
android:onClick="onClick"
/>
<RadioGroup
android:id="@+id/rg"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<RadioButton
android:id="@+id/rbMale"
android:text="男"
android:checked="true"
android:onClick="onClick"
/>
<RadioButton
android:id="@+id/rbfaMale"
android:text="女"
android:onClick="onClick"/>
<CheckBox
android:id="@+id/cbMale"
android:text="变男"
android:onClick="onClick"/>
<CheckBox
android:id="@+id/cbfaMale"
android:text="变女"
android:onClick="onClick"/>
</RadioGroup>
</LinearLayout>
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.widget.CheckBox;
import android.widget.ImageView;
import android.widget.RadioButton;
import android.widget.TextView;
public class MainActivity extends ActionBarActivity {
private RadioButton rbMale ;//初始化-----男
private RadioButton rbfaMale ;//初始化------女
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
init();
}
private void init(){//初始化 ----男,女
rbMale = (RadioButton) findViewById(R.id.rbMale);
rbfaMale = (RadioButton) findViewById(R.id.rbfaMale);
}
public void onClick(View v){
Log.i("main", v.getId()+"");
switch (v.getId()) {
case R.id.tv:
TextView tv = (TextView)v;
Log.i("main", tv.getText().toString());
tv.setTextColor(Color.RED);
break;
case R.id.iv:
ImageView iv = (ImageView)v;
iv.setImageResource(R.drawable.p01);
break;
case R.id.cbMale:
CheckBox cb = (CheckBox)v;
rbMale.setChecked(cb.isChecked());
rbfaMale.setChecked(!cb.isChecked());
break;
case R.id.cbfaMale:
CheckBox cbfa = (CheckBox)v;
rbMale.setChecked(!cbfa.isChecked());
rbfaMale.setChecked(cbfa.isChecked());
break;
}
}
}
效果:
转载于:https://blog.51cto.com/qa962839575/1587114