gpt4 book ai didi

android - ImageButton 属性检查

转载 作者:行者123 更新时间:2023-11-30 04:29:34 25 4
gpt4 key购买 nike

我有一个 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com