cphelps76 February 2016

findViewByIdlayoutinflator fails to inflate my layouts, returns null when using

my main activity calls for view to inflate my main.xml but whatever reason always seems to return null, i'm kind of lost here since this worked in 4.2 but now doesn't after upgrading the rest of my source to 6.0

    @Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    LayoutInflater inflater = (LayoutInflater) this.getSystemService(
            Context.LAYOUT_INFLATER_SERVICE);

    View layout = inflater.inflate(R.layout.main, null);

    setContentView(layout);

    ctx = this;

    prefs = PreferenceManager.getDefaultSharedPreferences(this);
    res = getResources();

    mAudioManager = (AudioManager)getSystemService(Context.AUDIO_SERVICE);

    mMediaButtonReceiver = new RemoteControlReceiver();
    mediaFilter = new IntentFilter(Intent.ACTION_MEDIA_BUTTON);
    mediaFilter.setPriority(Integer.MAX_VALUE);

    registerReceiver(mMediaButtonReceiver, mediaFilter);

    //mDrawable = (this.res.getDrawable(R.drawable.glowy_metal));
    //mBackground.setBackgroundDrawable(mDrawable);
    mBackground = (ImageView) layout.findViewById(R.id.background);
    mBackground.setOnTouchListener(new backgroundTouchListener());

logcat shows null here:

mBackground = (ImageView) layout.findViewById(R.id.background);

the background id in my main.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical">
    <ImageView
        android:id="@+id/background"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:layout_alignParentLeft="true"
        android:layout_alignParentTop="true"
        android:scaleType="fitCenter"
        android:background="@drawable/glowy_metal"/>

can anyone shed

Answers


George Mulligan February 2016

Just use

setContentView(R.layout.main);

and then later

mBackground = (ImageView) findViewById(R.id.background);

No need to create a new inflater since the Activity already has methods to do what you want.

Post Status

Asked in February 2016
Viewed 1,830 times
Voted 10
Answered 1 times

Search




Leave an answer