![](/img/trans.png)
[英]Passing data from a class that 'extends activity' to a class that 'extends fragment'
[英]How to get the View for a class, that extends a class that extends Fragment/activity etc
我有一个问题,如果我有:
class x 延伸 y
和 class y 扩展片段
我希望能够在 x 中做一些事情,例如获得一个带有 ID 的 textview 并更改文本。 要做到这一点,我必须获得观点,但我遇到了问题。 我尝试过 Super.getView,并尝试将视图保存在 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 保存为TextView
中的受保护变量,该变量扩展片段,以便您可以从其子类访问它:
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...
}
}
}
请记住,它只会在该片段上调用 onViewCreated 之后分配onViewCreated
,但您可以在执行任何操作之前检查它是否已定义(它不为空)。
PS:在扩展Activity
的情况下,可以通过调用该 Activity 的findViewById
方法在onCreate
方法中分配:
public class x extends Activity {
protected TextView myTextView;
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
....
myTextView = findViewById(...);
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.