Mizzeeboy
Mizzeeboy

Reputation: 31

"findViewById" not working in ViewPagerIndicator Fragment

Hi there I have managed to bind my XML files to the ViewPagerIndicator by extending them as Fragments but I cannot use the essential findViewById code to reference my button to the code. This is my code as it is can someone help

    package com.example.sliding;

import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;

public class twoey extends Fragment {

    Button lol;

    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState){
        View v = inflater.inflate(R.layout.two, null);
        return v;

        lol = (Button) findViewById (R.id.button1);

    }
}

But what ever I try to do I cannot get the little red wriggly line of the findViewById word can someone help ?

Upvotes: 0

Views: 1527

Answers (3)

madlymad
madlymad

Reputation: 6530

Your code has 2 errors:

  1. return v; must be the last line of a method, any line after that cannot be run! is unreachable so there is a compiler error!

  2. the line lol = (Button) findViewById (R.id.button1); needs to be lol = (Button) v.findViewById (R.id.button1); or you are going to have a NullPointerException because button1 is part of View v and not the activity.

The right code is:

public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    View v = inflater.inflate(R.layout.two, null);

    lol = (Button) v.findViewById (R.id.button1);
    return v;
}

Upvotes: 3

Siddharth Lele
Siddharth Lele

Reputation: 27748

Override the onViewCreated(). Like this:

@Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
    lol = (Button) getView().findViewById (R.id.button1);

    .... // ANY OTHER CASTS YOU NEED TO USE IN THE FRAGMENT
}

Upvotes: 0

Egor
Egor

Reputation: 40193

Java compiler simply can't access code written after the return statement. return means you're done with the method and you're returning a value from it, so there's no sense in executing something after that. So you need to simply move the lol = (Button) findViewById (R.id.button1) (which as a matter of fact should be called as lol = (Button) v.findViewById (R.id.button1), since v is your root view) before the return v call, and the code will compile properly. Hope this helps.

Upvotes: 0

Related Questions