Android学习之路二:Button,ImageButton和ToggleButton

  Button就是我们了解的软件中的按钮,我们可以通过添加按钮的监听机制来实现按钮点击后的功能;

  ImageButton是图片按钮,它的功能呢基本跟Button一样,但是它可以显示的按钮风格跟Button不一样;

  ToggleButton是开关按钮,它有两种状态。  

     

  Button案例:

  java代码:

 

       Button myButton = (Button) findViewById(R.id.myButton);
       myButton.setText("按我");
        //设置监听机制,处理Button被点击后的事件
        myButton.setOnClickListener(new OnClickListener() {
            
            public void onClick(View arg0) {
                // 此处为点击后的事件
            }
        });

  XML代码:

<Button
        android:id="@+id/myButton"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        />

  ImageButton案例:

  java代码:

        ImageButton myButton = (ImageButton) findViewById(R.id.myButton);
        myButton.setVisibility(View.VISIBLE);
        myButton.setOnClickListener(new OnClickListener() {
            public void onClick(View arg0) {
                // 此处为点击后的事件
                Toast.makeText(MainActivity.this, "您已经点击了该按钮", Toast.LENGTH_SHORT).show();
            }
        });

  XML代码:

<ImageButton
        android:id="@+id/myButton"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:contentDescription="@string/imgbut"
        android:background="@drawable/ic_launcher"/>

  ToggleButton案例:

  java代码:

        final ToggleButton myButton = (ToggleButton) findViewById(R.id.myButton);
        myButton.setOnCheckedChangeListener(new OnCheckedChangeListener() {
            
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                // 此处可以通过isChecked参数进行逻辑处理
                if(myButton.isChecked()){
                    Toast.makeText(MainActivity.this, "已经关闭", Toast.LENGTH_SHORT).show();
                }else{
                    Toast.makeText(MainActivity.this, "已经开启", Toast.LENGTH_SHORT).show();
                }
            }
        });

  XML代码:

<ToggleButton
        android:id="@+id/myButton"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"/>

 

 

  

 

转载于:https://www.cnblogs.com/thinksasa/archive/2013/02/20/2918399.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值