android - ImageButton 属性检查

标签 android background android-alertdialog imagebutton

我有一个 ImageButton,单击它会显示一个对话框,用户可以在其中从相机拍摄照片或从图库中选择。从任一来源选择图像时,我将该 ImageButton 的位图设置为这样选择的图像

SelectedPhoto = BitmapFactory.decodeFile(selectedImagePath);
DisplayPhoto.setImageBitmap(SelectedPhoto);

现在,当有人已经选择了一张图片并再次单击该图片时,我想显示一个不同的对话框,其中包含第三个选项“删除照片”。

我应该检查图像按钮的什么属性?

XML 中的图像按钮

<ImageButton
                android:id="@+id/DisplayPhoto"
                android:layout_width="95dip"
                android:layout_height="95dip"
                android:layout_marginRight="8dip"
                android:background="@drawable/signup_photo_selector" android:scaleType="centerCrop" />

ImageButton 背景 XML

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:drawable="@drawable/signup_form_photo_selected" android:state_pressed="true"/>
    <item android:drawable="@drawable/signup_form_photo"/>
</selector>

最佳答案

imgButton.getDrawable() 会工作吗,因为如果没有为 imagebutton 分配可绘制对象,它会返回 null?

如果没有,或者如果您不想获取整个可绘制对象只是为了查看它是否存在,您可以使用标签。 imgButton.setTag(object) 允许您在图像按钮中存储任何对象...每次设置其背景时,您都可以标记一个值来标识其背景是否已设置。如果有用的话,您甚至可以使用不同的值来区分您是使用相机还是从画廊设置背景。当您想查看图像按钮是否有背景时,请使用 imgButton.getTag() 来检索对象。

编辑。以下是您将如何使用 setTag 和 getTag。我将使用一个 Integer 对象作为 ImageButton 的标签,其中 0 值表示未设置背景,1 值表示已设置背景。如果您想让代码更清晰一些,您可以使用枚举或最终变量,但使用 Integer 将作为示例。

public class MainActivity extends Activity, implements OnClickListener {
  private ImageButton imgButton;

  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    imgButton = (ImageButton)findViewById(R.id.imgID);
    imgButton.setTag(new Integer(0)); // no background
    ...
  }

  public void onClick(View view) {
    ImageButton ib = (ImageButton)view;
    int hasBackground = ib.getTag().intValue();

    if(hasBackground==0) {
      // imagebutton does not have a background. do not include remove option
      ...
    } else {
      // imagebutton has a background. include remove option
    }
  }
}

关于android - ImageButton 属性检查,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7945886/

相关文章:

CSS - CSS3 像素化点背景

c# - Android AlertDialog,不要在按键时关闭,而是在触摸时关闭

android - 使用 LayoutInflater 和 AlertDialog

php - wordpress 视频不适用于移动设备

background - 从多任务处理回来后如何恢复 CAAnimation

android - alertDialog 无法正常工作

android - 当我点击设备后退按钮 android 时应用程序崩溃

android - 为多个 View 设置动画会导致动画卡住

android - 错误: Class is referenced as a converter but it does not have any converter methods

java - 在 Android 中从服务器获取和发送数据的最佳方法