在Android开发中,如何在新建fragment实例时创建一个fragment的tag属性使得该fragment能够通过findFragmentByid()方法被找到
时间: 2024-05-16 17:12:21 浏览: 13
在新建 Fragment 实例时,可以通过调用 FragmentTransaction 的 `add()` 方法来添加 Fragment 到 Activity 中,例如:
```java
MyFragment fragment = new MyFragment();
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
transaction.add(R.id.fragment_container, fragment, "MY_FRAGMENT_TAG");
transaction.commit();
```
在上面的代码中,我们在添加 Fragment 时传入了一个 tag 字符串 "MY_FRAGMENT_TAG",这样就可以通过该 tag 属性来查找对应的 Fragment 实例,例如:
```java
MyFragment fragment = (MyFragment) getSupportFragmentManager().findFragmentByTag("MY_FRAGMENT_TAG");
if (fragment != null) {
// 找到了对应的 Fragment 实例
} else {
// 没有找到对应的 Fragment 实例
}
```
注意,`findFragmentById()` 方法是基于 Fragment 的 ID 来查找 Fragment 实例的,而不是基于 tag 属性。因此,如果要使用 `findFragmentById()` 方法来查找 Fragment 实例,则需要在添加 Fragment 时为其设置一个唯一的 ID,例如:
```java
MyFragment fragment = new MyFragment();
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
transaction.add(R.id.fragment_container, fragment, "MY_FRAGMENT_TAG");
transaction.addToBackStack(null);
transaction.commit();
```
在上面的代码中,我们在添加 Fragment 时,通过 `R.id.fragment_container` 为其设置了一个唯一的 ID。这样,我们就可以通过 `findFragmentById()` 方法来查找对应的 Fragment 实例,例如:
```java
MyFragment fragment = (MyFragment) getSupportFragmentManager().findFragmentById(R.id.fragment_container);
if (fragment != null) {
// 找到了对应的 Fragment 实例
} else {
// 没有找到对应的 Fragment 实例
}
```
总之,无论是使用 tag 属性还是 ID 属性,都可以通过 FragmentTransaction 的 `add()` 方法来添加 Fragment 实例,并通过 `findFragmentByid()` 或 `findFragmentByTag()` 方法来查找对应的 Fragment 实例。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.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)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)