在片段中添加按钮?

11 浏览
0 Comments

在片段中添加按钮?

这个问题已经在这里有了答案:

在Fragment中的findViewById

我正在尝试向我的fragment布局中添加一个按钮,但它说方法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);
    }
}

admin 更改状态以发布 2023年5月20日
0
0 Comments

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

使用以上代码

0
0 Comments

你需要使用View。例如,

@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;
}

0