在android 中事件的点击是非常重要的,当你的程序要有些交互操作的时候,就需要你对不同的组件进行操作。这样你就会用到事件的操作
下面给大家讲解一个入门级的操作,单击事件。
单击事件也是android中最常见的事件也是最重要的事件之一。
首先你要定义你的视图:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical"
android:id="@+id/myOnclickId">
<EditText android:id="@+id/myOnclickET"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
/>
<Button android:id="@+id/myOnclickBT"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="点击事件"/>
<TextView android:id="@+id/myOnclickTV"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="您输入的文字是:"/>
</LinearLayout>
视图的功能是点击button按键在tv中显示et的内容
publicclass myOnclick extends Activity{
private EditText et;
private Button bt;
private TextView tv;
public EditText getEt() {
returnet;
}
publicvoid setEt(EditText et) {
this.et = et;
}
public Button getBt() {
returnbt;
}
publicvoid setBt(Button bt) {
this.bt = bt;
}
public TextView getTv() {
returntv;
}
publicvoid setTv(TextView tv) {
this.tv = tv;
}
protectedvoid onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
super.setContentView(R.layout.myonclick);
this.et=(EditText)super.findViewById(R.id.myOnclickET);
this.bt=(Button)super.findViewById(R.id.myOnclickBT);
this.tv=(TextView)super.findViewById(R.id.myOnclickTV);
this.bt.setOnClickListener(new myOnclickImpl());
}
}
myOnclickImpl 我们在这里一般不才用直接写内部类的方式,而是写一个类去继承OnClickListener,这样你的单击事件就可以复用(在写代码的时候,注意重点要考虑你的代码的可读性,可维护性,简单点就是重复的代码最好不要写)。
publicclass myOnclickImpl implements OnClickListener {
publicvoid onClick(View v) {
if(v.getId()==R.id.myOnclickBT){
myOnclick my1=(myOnclick)v.getContext();
my1.getTv().setText(my1.getEt().getText().toString());
}
}
}
在这里有2行代码大家要注意点,一个是v.getId()==R.id.myOnclickBT 这行代码是当你又很多按键触发的时候,都是用的这个类,你不知道是哪个按键触发的这个方法时候,就可以用这样的方法去判断。还有一个实例化一个对象的时候,不能写成new的方式这样往往出现的是空指针异常,所以要用myOnclick my1=(myOnclick)v.getContext();
这样的方式去实例化一个对象。onClick处理的逻辑就写在这个方法里面(必须要实现的)
在后面会给大家介绍些高级的时间处理方法。