activity 获取根view
时间: 2023-07-27 07:07:16 浏览: 57
您可以使用以下代码获取根View:
```java
View rootView = activity.getWindow().getDecorView().findViewById(android.R.id.content);
```
其中,activity 为您的 Activity 实例。该代码会获取到当前 Activity 的根 View。
相关问题
activity获取fragment控件
要获取Fragment中的控件,可以通过以下步骤:
1. 在Fragment中定义控件变量,例如:
```
private TextView mTextView;
```
2. 在Fragment的onCreateView()方法中,使用LayoutInflater来加载布局文件,并返回根视图:
```
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_layout, container, false);
return rootView;
}
```
3. 在onViewCreated()方法中,使用findViewById()方法来获取控件:
```
@Override
public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
mTextView = view.findViewById(R.id.text_view);
}
```
4. 现在就可以在Fragment中使用mTextView控件了,例如:
```
mTextView.setText("Hello Fragment!");
```
Activity获取fragment的控件
可以通过在Fragment中使用getView()方法获取Fragment的根视图,然后使用findViewById()方法获取其中的控件。
例如,在Fragment中获取一个TextView控件的代码如下:
```java
public class MyFragment extends Fragment {
private TextView mTextView;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View rootView = inflater.inflate(R.layout.fragment_my, container, false);
mTextView = rootView.findViewById(R.id.my_text_view);
return rootView;
}
}
```
在上面的代码中,onCreateView()方法中使用了inflater.inflate()方法来加载Fragment的布局文件,然后使用findViewById()方法获取了其中的TextView控件。获取到的控件可以在Fragment中进行操作。
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![.zip](https://img-home.csdnimg.cn/images/20210720083646.png)
![7z](https://img-home.csdnimg.cn/images/20210720083312.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)