Android ImageButton 选中与不选中 不同状态之间显示不同图片的方式

本文介绍如何使用XML配置ImageButton,并根据不同状态显示不同的图标。通过代码控制按钮的选中状态,实现图标的变化。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1.用xml配置 the ImageButton defined in the following layout.

  <ImageButton
            android:id="@id/rte_bold"
            android:layout_width="40dip"
            android:layout_height="40dip"
            android:src="@drawable/rte_bold_state"
            android:scaleType="fitXY"
            android:layout_marginTop="5dip"
            android:textSize="10dip" />


2.The rte_bold_state layout xml below, in different states("selected" and "unselected") show different drawbles .

<?xml version="1.0" encoding="UTF-8"?>  
<selector xmlns:android="http://schemas.android.com/apk/res/android">  
     <item android:state_selected="true" android:drawable="@drawable/rte_bold_selected" />  
     <item android:drawable="@drawable/rte_bold" />   
</selector> 


3.下面的代码来控制是否选中,从而来改变图片:

boldButton = (ImageButton) view.findViewById(R.id.rte_bold);

    boldButton.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {

             if (boldButton.isSelected()) {
             boldButton.setSelected(false);
             }
           else {
                  boldButton.setSelected(true);
               }
  
        });



如有问题请您指正,我就是一个Android小菜鸟。





Android 单击选中ImageButton[]图像数组用法示例,类似于Radio的功能,过用图片表现,这样可使Android UI更加友好,视觉更漂亮一些,用户轻触图片,即可选中该数据项,比Radio用户体验更好,如截图所示的选中效果选中后图像会变色:   setContentView(R.layout.main);   myTextView = (TextView) this.findViewById(R.id.myTextView);//得到myTextView的引用   imageButtons[0] = (ImageButton) this.findViewById(R.id.button01);//得到button01的引用   imageButtons[1] = (ImageButton) this.findViewById(R.id.button02);//得到button02的引用   imageButtons[2] = (ImageButton) this.findViewById(R.id.button03);//得到button03的引用   imageButtons[3] = (ImageButton) this.findViewById(R.id.button04);//得到button04的引用   for(ImageButton imageButton : imageButtons){   imageButton.setOnFocusChangeListener(this);//添加监听   我们同时使用了if else来判断各个ImageButton数组元素的选中状态:   实现了接口中的方法   if(v.getId() == R.id.button01){//改变的是button01时    myTextView.setText("您选中了羊!");   }else if(v.getId() == R.id.button02){//改变的是button02时    myTextView.setText("您选中了猪!");   }else if(v.getId() == R.id.button03){//改变的是button03时    myTextView.setText("您选中了牛!");   }else if(v.getId() == R.id.button04){//改变的是button04时    myTextView.setText("您选中了鼠!");   }else{//其他情况    myTextView.setText("");   }
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值