fragment如何隐藏activity中的控件
时间: 2024-05-02 12:16:48 浏览: 15
在 Android 中,可以使用 Fragment 来隐藏 Activity 中的控件。具体做法如下:
1. 在 Activity 的布局文件中,使用 `<fragment>` 标签来添加 Fragment。
2. 在 Fragment 的布局文件中,添加需要显示的控件。
3. 在 Fragment 的代码中,使用 `getView().setVisibility(View.GONE)` 来隐藏控件。
例如,如果要隐藏 Activity 中的一个 Button,可以按照以下步骤进行操作:
1. 在 Activity 的布局文件中,添加一个 Fragment:
```
<fragment
android:id="@+id/my_fragment"
android:name="com.example.MyFragment"
android:layout_width="match_parent"
android:layout_height="match_parent" />
```
2. 在 Fragment 的布局文件中,添加一个 Button:
```
<Button
android:id="@+id/my_button"
android:text="Hide me!"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
```
3. 在 Fragment 的代码中,获取 Button 对象并隐藏它:
```
public class MyFragment extends Fragment {
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_my, container, false);
Button myButton = view.findViewById(R.id.my_button);
myButton.setVisibility(View.GONE);
return view;
}
}
```
这样,在 Activity 中就可以通过添加 Fragment 来隐藏控件了。