-7

Hello, I have a Fragment for a ViewPager:

package my.test.myapplication;

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

public class Fragment1 extends Fragment {

    private Button btn;
    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        // point A
        return  inflater.inflate(R.layout.frag1,container,false);
    }
}

When I would add this under point A, it comes a error message:

public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    // point A
    btn = (Button) findViewById(R.id.button);
    return  inflater.inflate(R.layout.frag1,container,false);
}

The error message:

Cannot resolve method 'findViewById(int)'

What can I do?

ThePi
  • 67
  • 2
  • 6

6 Answers6

3

If you want to access any view, you have view object to access it.

  public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
          View view =   inflater.inflate(R.layout.frag1,container,false);
         btn = (Button)view.findViewById(R.id.button);

       return view;
   }
Tejas
  • 358
  • 5
  • 22
1

try this if want to bind your controls in fragment than your have to first get the your layout in to a view using LayoutInflater than with the help of that view you can bind your all controls like this

public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View rootView = inflater.inflate(R.layout.frag1,container,false);
        btn = (Button) rootView.findViewById(R.id.button);
        return rootView  ;
    }
AskNilesh
  • 63,753
  • 16
  • 113
  • 150
0

Try below code in OnViewCreated() method:

btn = (Button) view.findViewById(R.id.button);
nivesh shastri
  • 420
  • 2
  • 13
0

Try that

 view.findViewById(R.id.expandable);
Harshit Trivedi
  • 726
  • 9
  • 28
0

You can try like this:

public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) 
{
  View rootView = inflater.inflate(R.layout.frag1, container, false);
  btn = (Button)rootView.findViewById(R.id.button);
  return  rootView ;
}
Vishal Vaishnav
  • 3,208
  • 2
  • 22
  • 53
0

A Fragment is not a subclass of Activity.

You have to call findViewById(R.id.*id*); on a Activity object.

See API.