Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

adding a button in a fragment? [duplicate]

I'm trying to add a button to my fragment layout but it says that the method findViewByid cannot be resolved. I'm implementing it in the onCreateView method in the fragment. Why is it giving me this error?

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

public class extra extends Fragment {


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        Button myButton = (Button) findViewById(R.id.my_button);
        return inflater.inflate(R.layout.extra, container, false);

    }

}
like image 248
asdddd Avatar asked Oct 24 '25 01:10

asdddd


3 Answers

You need to use View. like,

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
        Bundle savedInstanceState) {

    View rootView = inflater.inflate(R.layout.extra, container, false);
      // Inflate the layout for this fragment
    Button myButton = (Button) rootView.findViewById(R.id.my_button);

    return rootView;
}
like image 94
Sathish Kumar J Avatar answered Oct 26 '25 14:10

Sathish Kumar J


You need to use View. like,

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
        Bundle savedInstanceState) {

    View rootView = inflater.inflate(R.layout.extra, container, false);
      // Inflate the layout for this fragment
    Button myButton = (Button) rootView.findViewById(R.id.my_button);

    return rootView;
}
like image 20
Sathish Kumar J Avatar answered Oct 26 '25 16:10

Sathish Kumar J


public class extra extends Fragment {
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    // Inflate the layout for this fragment
  View v = LayoutInflater.from(getActivity()).inflate(
            R.layout.YOUR_LAYOUT, null);

    Button myButton = (Button) v.findViewById(R.id.my_button);
    return v;
}}

Use above code

like image 36
PriyankaChauhan Avatar answered Oct 26 '25 15:10

PriyankaChauhan