Button监听器的五种方式

第一种:内部类的方式

class MyButton implements OnClickListener{
                @Override
                public void onClick(View v) {
                        // TODO Auto-generated method stub

                        Toast.makeText(MainActivity.this, "我被点击了!", Toast.LENGTH_SHORT).show();
                }
        }

第二种:匿名内部类的方式

button.setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View v) {
                        // TODO Auto-generated method stub
                        Toast.makeText(MainActivity.this, "我又被点击了!", Toast.LENGTH_SHORT).show();
                }
        });

第三种:外部类方式

public class MyOnClickListener implements OnClickListener {
                @Override
                public void onClick(View v) {
                        // TODO Auto-generated method stub

                        System.out.println("我第四次被点击了!");
                }
        }
        .........................................
        MyOnClickListener clickListener = new MyOnClickListener();
        button.setOnClickListener(clickListener);*/

第四种:Activity本身方式

public class MainActivity extends Activity implements OnClickListener {
                .......................
                public void onClick(View v) {
                        // TODO Auto-generated method stub
                        Toast.makeText(, "我第四次被点击了!", Toast.LENGTH_SHORT).show();
                }
                ...............................
        }

第五种:绑定标签

<Button 
                android:id="@+id/button"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="@string/hello_world"
                android:onClick="MyListener"
        />

在Activity中实现方法MyListener()

public void MyListener(View view)
        {
                Toast.makeText(MainActivity.this, "我第五次被点击了!", Toast.LENGTH_SHORT).show();
        }

上一篇:目录


下一篇:Menu相关