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/p/2918399.html