gpt4 book ai didi

android - setColorFilter 显示空对象引用

转载 作者:行者123 更新时间:2023-11-30 01:41:25 24 4
gpt4 key购买 nike

我创建了一个名为btn.xml 的布局资源文件,它包含ImageView。在主要 Activity 中,我在 content_main.xml 中膨胀 btn.xml,并尝试设置膨胀 View 的背景。但它向我显示:Drawable.setColorFilter(int, android.graphics.PorterDuff$Mode)' on a null object reference

在 mainActivity 中编写 java 代码:

View v;
RelativeLayout rlt;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
LayoutInflater myInflater = (LayoutInflater) getApplicationContext().getSystemService(getApplicationContext().LAYOUT_INFLATER_SERVICE);
v = myInflater.inflate(R.layout.btn,null,false);
// Here is the probelm :
v.getBackground().setColorFilter(Color.parseColor("#00ff00"), PorterDuff.Mode.DARKEN);
rlt = (RelativeLayout) findViewById(R.id.rlt);
rlt.addView(v);
}

content_main.xml 布局:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
app:layout_behavior="@string/appbar_scrolling_view_behavior"
tools:context="com.example.othma.tjkljklj.MainActivity"
tools:showIn="@layout/activity_main"
android:id="@+id/rlt">

<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!"
android:id="@+id/textView" />

</RelativeLayout>

btn.xml布局资源文件

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

<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/imgv1"
android:src="@drawable/continu" />
</LinearLayout>

最佳答案

如您所见,在您的 btn.xml 文件中您没有为您的 View 设置任何可绘制对象(线性布局),因此您得到了一个空对象引用错误。 p>

setColorFilter() 方法指定一个颜色Porter-Duff 模式作为< strong>可绘制。

例如;如果你想改变 imageview drawable(或任何 view drawable)的颜色,你应该使用 setColorFilter() 方法。

imageview.getDrawable().setColorFilter(color, mode);

如果您想更改 View 的背景颜色,则应使用 setBackgroundColor() 方法。

view.setBackgroundColor(getResources().getColor(R.color.anycolor)); 

关于android - setColorFilter 显示空对象引用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34456261/

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