android-fragments 我想添加片段按钮,但它不起作用

xjreopfe  于 2022-11-14  发布在  Android
关注(0)|答案(1)|浏览(116)

我是Android新手,我想像在Activity中一样添加片段按钮,但我无法将其添加到要添加的位置(当我尝试将其添加到任何位置时,findViewById未出现)

private ImageView walleticon;
    private static final String ARG_PARAM1 = "param1";
    private static final String ARG_PARAM2 = "param2";

    private String mParam1;
    private String mParam2;

    public static SatisFragment newInstance(String param1, String param2) {
        SatisFragment fragment = new SatisFragment();
        Bundle args = new Bundle();
        args.putString(ARG_PARAM1, param1);
        args.putString(ARG_PARAM2, param2);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            mParam1 = getArguments().getString(ARG_PARAM1);
            mParam2 = getArguments().getString(ARG_PARAM2);
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment_satis, container, false);
    }
    public SatisFragment(){

    }
}```
h7wcgrx3

h7wcgrx31#

在片段中,视图以不同的方式访问。
在您使用的“活动”中,setContentView(R.layout.activity_main);这允许直接调用findViewById(R.id.button);
在Fragment中,findViewById只存在于单个视图级别。

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    View view = inflater.inflate(R.layout.fragment_satis, container, false);
    Button button = view.findViewById(R.id.button); //<-- Here is your button
    return view;
}

相关问题