事件的定义方法,分为三种,分别为在 中进行指定方法;在Actitivy中new出一个 Listenner();实现 Listener接口三种方式。

1.在 中实现方法的绑定

    <Button        android:id="@+id/btn_add"        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:layout_alignLeft="@+id/editText1"        android:layout_below="@+id/editText1"        android:layout_marginTop="46dp"        android: ="btnadd"        android:text="+" />

在MainActivity中实现绑定的方法btnadd

   public void btnadd(View v)    {        //绑定的btnadd方法        Toast.makeText(getApplicationContext(), "我是绑定方法", Toast.LENGTH_LONG).show();    }

 

2.NEW一个 Listenner()接口实例

    @Override    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.activity_main);                //关联控件        btn_add=(Button) findViewById(R.id.btn_add);        btn_reduce=(Button) findViewById(R.id.btn_reduce);        et=(EditText) findViewById(R.id.editText1);        //第二种,接口实例化        btn_add.set Listener(new  Listener() {                        @Override            public void  (View v) {                // TODO Auto-generated method stub                            }        });    }

上面这种是最为常见一种实现方法,为了让oncreat中的代码更清晰,我们也会是用另一种写法

    btn_add.set Listener(add);

实现add方法:

     Listener add =new  Listener() {                @Override        public void  (View v) {            // TODO Auto-generated method stub                    }    };

3.实现 Listener接口

  首先类要引用 Listener接口,并实现方法

public class MainActivity extends Activity implements  Listener{        @Override    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.activity_main);                //关联控件        btn_add=(Button) findViewById(R.id.btn_add);        btn_reduce=(Button) findViewById(R.id.btn_reduce);        et=(EditText) findViewById(R.id.editText1);        //第三种,使用接口        btn_add.set Listener(this);        btn_reduce.set Listener(this);    }    @Override    public void  (View v) {        // TODO Auto-generated method stub        switch(v.getId())        {        case R.id.btn_add:                        break;        case R.id.btn_reduce:                        break;        }            }}

 

遗失的拂晓
收藏 打印