置换颜色的机关(Button和TextView的交互)
新建一个继承Activity类的ChangeTextViewColorActivity,并设置布局文件为:changetextviewcolor.xml。
在布局文件中,新建一个TextView和Button组件。
<TextView android:id="@+id/changetextviewcolor_tv01" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="center_horizontal" android:text="@string/textviewcoloractivity" android:textSize="18sp" /> <Button android:id="@+id/changetextviewcolor_btn01" style="@android:style/Widget.Button.Inset" android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="@string/change_color" android:textSize="18sp" /> |
而后在Activity代码中得到Button和TextView组件的实例化对象并设置Button 的单击事件。
在Button的事件处理中,设置TextView的颜色,这里通过Random类随机获取一组颜色值来设置TextView的颜色。具体的代码如下:
package lyx.feng.simpletextdemo; ...... public class ChangeTextViewColorActivity extends Activity implements OnClickListener { private Button btn = null; private TextView tv = null;
@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); super.setContentView(R.layout.changetextviewcolor); this.btn = (Button) super.findViewById(R.id.changetextviewcolor_tv01); this.tv = (TextView) super.findViewById(R.id.changetextviewcolor_btn01);
this.btn.setOnClickListener(this); }
@Override public void onClick(View v) { int alpha = new Random().nextInt(255); int red = new Random().nextInt(255); int green = new Random().nextInt(255); int blue = new Random().nextInt(255); this.tv.setText("alpha:" + alpha + ",red:" + red + ",green:" + green + ",blue:" + blue); this.tv.setTextColor(Color.argb(alpha, red, green, blue)); } }
|
运行后的效果:
点击按钮后的效果: