Issue
I create a layout resource file named btn.xml, it contains ImageView. in main activity i inflate btn.xml in content_main.xml and i try to set background of inflated View. but it shows me : Drawable.setColorFilter(int, android.graphics.PorterDuff$Mode)' on a null object reference
code java in mainActivity :
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 Layout :
<?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 layout Resource file
<?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>
Solution
in your btn.xml file as you see you did not set any drawable to your view(linearlayout), so you got a null object reference error.
setColorFilter() method specify a color and Porter-Duff mode to be the color filter for drawable.
For example; if you want to change imageview drawable(or any view drawable) color, you should use setColorFilter() method.
imageview.getDrawable().setColorFilter(color, mode);
if you want to change background color of your view, then you should use setBackgroundColor() method.
view.setBackgroundColor(getResources().getColor(R.color.anycolor));
Answered By - settaratici
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.