我的计划是在用户触摸行时从我的RecyclerView适配器中的ImageView更改矢量颜色。我只是想改变触摸行的颜色。我写了一个代码应该做这个工作,但我收到一个错误:
java.lang.NullPointerException: Attempt to invoke virtual method 'int android.content.Context.getColor(int)' on a null object reference
我已经尝试了很多,但错误总是一个问题。
这是我的RecyclerView行xml:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_height="match_parent"
android:layout_width="match_parent"
android:focusable="true"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:clickable="true"
android:background="?android:attr/selectableItemBackground"
android:orientation="vertical">
<!-- Setting icon -->
<ImageView
android:id="@+id/settingImage"
android:layout_width="24dp"
android:layout_height="24dp"
android:layout_centerVertical="true"
android:layout_alignParentStart="true"
android:layout_marginRight="8dp"
android:layout_marginTop="1dp"
android:layout_marginBottom="1dp"
android:contentDescription="Icon"
android:src="@mipmap/ic_launcher" />
<!-- Setting title -->
<TextView
android:id="@+id/settingTitle"
android:textColor="@color/colorBlack"
android:layout_width="match_parent"
android:layout_marginLeft="40dp"
android:layout_marginTop="14dp"
android:textSize="16dp"
android:layout_height="wrap_content" />
<!-- Setting subtitle -->
<TextView
android:id="@+id/settingSubtitle"
android:layout_below="@id/settingTitle"
android:layout_marginBottom="14dp"
android:layout_marginLeft="40dp"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
</RelativeLayout>
这是我想要更改填充颜色的矢量图形:
<vector xmlns:android="http://schemas.android.com/apk/res/android"
android:width="24dp"
android:height="24dp"
android:viewportHeight="24.0"
android:viewportWidth="24.0">
<path
android:fillColor="@color/iconGray"
android:pathData="M10.09 15.59L11.5 17l5-5-5-5-1.41 1.41L12.67 11H3v2h9.67l-2.58 2.59zM19 3H5c-1.11 0-2 .9-2 2v4h2V5h14v14H5v-4H3v4c0 1.1.89 2 2 2h14c1.1 0 2-.9 2-2V5c0-1.1-.9-2-2-2z" />
</vector>
这是我想要在点击时更改颜色的适配器:
// Get setting holder type
holder.type = setting.getType();
// OnTouchListener for holder/vector color change
holder.itemView.setOnTouchListener(new View.OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
// Define setting holder
MySettingHolder holder = (MySettingHolder) (v.getTag());
// Set view for getting settingImage
View view = (View)v.getParent();
// ImageView for changing color
ImageView imageView = (ImageView) v.findViewById(R.id.settingImage);
// Define switch for line
switch (holder.type) {
// Case 1 = Logout
case 1:
// Change ImageView color
DrawableCompat.setTint(imageView.getDrawable(), ContextCompat.getColor(context, R.color.colorPrimary));
break;
case 2:
break;
default:
break;
}
return false;
}
});
答案 0 :(得分:0)
解决方案是改变背景:
旧:
<div id='nav_div'>@ViewBag.str_display</div>
新:
DrawableCompat.setTint(imageView.getDrawable(), ContextCompat.getColor(context, R.color.colorPrimary));