我会将其保存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
在该片段上调用 myTextView 后分配,但您可以在执行任何操作之前检查它是否已定义(它不为空)。
PS:在扩展的情况下,Activity
可以onCreate
通过调用该findViewById
活动的方法在方法中分配它:
public class x extends Activity {
protected TextView myTextView;
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
....
myTextView = findViewById(...);
}
}