如何在fragment里面使用findViewById查找按钮
时间: 2023-11-27 09:55:25 浏览: 39
在 Fragment 中使用 findViewById 查找按钮需要注意以下几点:
1.在 Fragment 中,需要使用 View 的 findViewById 方法来查找按钮,因为 Fragment 不会像 Activity 一样自动调用 setContentView 方法来设置布局。
2.需要使用 Fragment 的 getView 方法获取 Fragment 中的视图 View。
下面是一个示例代码:
```
public class MyFragment extends Fragment {
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_my, container, false);
Button button = (Button) view.findViewById(R.id.button);
// 对 button 进行操作
return view;
}
}
```
在上面的代码中,首先使用 inflater.inflate 方法将布局文件 R.layout.fragment_my 转换为 View 对象,并返回给 Fragment,然后使用 getView().findViewById 方法查找按钮 R.id.button,并将其转换为 Button 对象。之后就可以对按钮进行相应的操作了。