gpt4 book ai didi

java - 如何获取类的 View ,该类扩展了扩展 fragment/Activity 等的类

转载 作者:行者123 更新时间:2023-12-01 22:23:41 25 4
gpt4 key购买 nike

我遇到了一个问题:

扩展 y 的类 x

以及扩展 Fragment 的 y 类

我希望能够在 x 中做一些事情,例如获取带有 ID 的 TextView 并更改文本。为此,我必须获得 View ,但我遇到了问题。我尝试过 Super.getView,并且尝试将 View 保存在 y 中并从 x 访问,但它不起作用。

这是为什么?

编辑:示例代码:

public x extends fragment{

}

public y extends x{
public y(){
eg TextView t = this.getView().getById(...)
which will fail as cant get the view
}
}

最佳答案

我会将 TextView 保存为扩展 fragment 的类中的 protected 变量,以便您可以从其子类访问它:

public class x extends Fragment {
protected TextView myTextView;

@Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);

myTextView = view.findViewById(...);
}
}

public class y extends x {
public void y() {
if (myTextView != null) {
myTextView...
}
}
}

请记住,只有在该 fragment 上调用 ​​onViewCreated 之后才会分配 myTextView,但您可以在执行任何操作之前检查它是否已定义(它不为空)。

P.S.:在扩展 Activity 的情况下,可以通过调用该 Activity 的 findViewById 方法在 onCreate 方法中进行分配:

public class x extends Activity {
protected TextView myTextView;

@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
....

myTextView = findViewById(...);
}
}

关于java - 如何获取类的 View ,该类扩展了扩展 fragment/Activity 等的类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58574448/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com