Java 在片段中添加按钮?

Java 在片段中添加按钮?,java,android,android-studio,android-fragments,Java,Android,Android Studio,Android Fragments,我试图在片段布局中添加一个按钮,但它表示无法解析方法findViewByid。我正在片段中的onCreateView方法中实现它。为什么它会给我这个错误 import android.support.v4.app.Fragment; import android.os.Bundle; import android.view.LayoutInflater; import android.view.ViewGroup; import android.view.View; import android

我试图在片段布局中添加一个按钮,但它表示无法解析方法
findViewByid
。我正在片段中的
onCreateView
方法中实现它。为什么它会给我这个错误

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);

    }

}
使用此代码:

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

    }

您需要使用
查看
。像

@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;
}
使用我的代码

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.extra, container, false);
Button myButton = (Button)view.findViewById(R.id.my_button);
return view;
}

使用上述代码

是因为您的类没有FindByView方法检查我的解决方案@asdddd
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;
}}