在android中单击设置图像视图

时间:2014-08-17 14:12:48

标签: android imageview

我有一个像按钮一样使用的图像视图,当我点击它开始动作时,现在我想在点击时更改imageView的背景,就好像它是一个普通的按钮。

例如:

 image view not hovered -> BackgroundImageViewNotHovered

 image view hovered -> BackgroundImageViewHovered
 ...

我的xml是这样的:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_gravity="center"
    android:gravity="center"
    android:orientation="vertical" >

    <ImageView
        android:id="@+id/button"
        android:layout_width="400dp"
        android:layout_height="100dp"
        android:src="@drawable/buttonImage" >
    </ImageView>

</LinearLayout>

我实现了一个像这样的监听器:

public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.foo_fragment, container, false);
        button = (ImageView) view.findViewById(R.id.login);
        button.setOnClickListener(new Action());
        return view;
    }

2 个答案:

答案 0 :(得分:1)

如果您正在谈论图像src,这里是一个解决方案。请尝试一下,让我知道

ImageButton button = (ImageButton)findViewById(R.id.login);

button.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
  button.setImageResource(R.drawable.<The image that you want>);
 }
}

答案 1 :(得分:1)

如果我们谈论ImageView的背景属性,您可以使用下一个代码:

ImageView imageButton = (ImageView) findViewById(R.id.button);

imageButton .setOnClickListener(new OnClickListener() 
{
  public void onClick(View v) 
  {
    imageButton.setBackgroundResource(R.drawable.your_background_image);
  }
}

UPD 1 。 如果你想使用带有按钮状态(选择器)的可绘制XML(我理解 buttonImage.xml ),你也应该使用字符串:

imageButton.setBackgroundResource(R.drawable.your_background_image);

而不是:

imageButton.setImageResource(R.drawable.your_background_image);
XML中的

或(它是相同的)

android:src="@drawable/buttonImage"