【问题标题】:ImageView onClick effect in fragment片段中的ImageView onClick效果
【发布时间】:2016-07-28 18:32:01
【问题描述】:

请纠正我的错误。我试图在 imageview click 上显示一些点击效果,但它抛出了 nullpointer 异常。这段代码我哪里错了?它在 createAllImage() 抛出空指针异常

片段代码

public class DuaFragment extends Fragment implements View.OnTouchListener {

    ImageView fear;

    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup  container, @Nullable Bundle savedInstanceState) {
        View view= inflater.inflate(R.layout.dua_fragment,container,false);
        return view;
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        createAllImage();
    }

    @Override
    public boolean onTouch(View view, MotionEvent motionEvent) {
        switch (motionEvent.getAction()) {
            case MotionEvent.ACTION_DOWN:
                fear.getDrawable().setColorFilter(0x77000000, PorterDuff.Mode.SRC_ATOP);
                fear.invalidate();
                break;
            case MotionEvent.ACTION_UP:
                fear.getDrawable().clearColorFilter();
                fear.invalidate();
                break;
        }
        return true;
    }

    void createAllImage() {
        fear=(ImageView)getView().findViewById(R.id.fear);
        fear.setOnTouchListener(this);
    }
}

我的布局文件

<ImageView
    android:id="@+id/fear"
    style="@style/icon"
    android:background="@drawable/fear_96" />

【问题讨论】:

  • 可能,fear.getDrawable() 返回 null 或者恐惧为 null.. 分享 stacktrace (logcat) 以获得更多帮助
  • fear.getDrawable() 正在抛出空指针,所以我将其更改为 setColorFilter(0x77000000, PorterDuff.Mode.SRC_ATOP); .现在它没有显示任何异常但没有点击效果
  • 你的 ImageView 有图片吗?
  • 是的,它是 9patch 图像
  • 好的。分享您的 ImageView 布局...您必须在 android:src 中设置 9Patch 图像(而不是在 android:background 中)。请检查一下

标签: android android-fragments android-imageview


【解决方案1】:

正如你提到的,fear.getDrawable() 正在返回 null。

所以,我们有两个解决方案..需要测试:

解决方案 1

fear.getDrawable() 为空,因为您将图片设置为android:background

我在 herehere 中创建了这个修复程序

所以,如下更改您的ImageView

<ImageView
    android:id="@+id/fear"
    style="@style/icon"
    android:src="@drawable/fear_96"
    android:scaleType="fitXY"       />

解决方案 2

如果你想在 ImageView 布局文件中保留android:background,尝试如下获取drawable:

fear.getBackgroundDrawable();

【讨论】:

  • Invalidate 强制视图重新绘制自身。发生这种情况是因为视图不知道您更改了可绘制对象。这就是为什么你必须“强制”
  • 解决方案一也可以正常工作。非常感谢@Guilherme。你能帮个忙吗,我不明白颜色代码 0x77000000。橙色的代码是什么
  • 0x77000000 是 AARRGGBB 中的一种颜色(Alpha、Red、Green、Blue)。您可以在 google 中搜索“AARRGGBB 格式的颜色”。橙色为 0xFFFF4500(注意 0x 表示该数字是十六进制格式)
  • 非常感谢,这对我很有帮助
  • 很高兴能帮到你:)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-10-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多