【问题标题】:How to get the View for a class, that extends a class that extends Fragment/activity etc如何获取一个类的视图,该类扩展了一个扩展片段/活动等的类
【发布时间】:2019-10-26 20:25:50
【问题描述】:

我遇到了问题:

扩展 y 的类 x

和扩展 Fragment 的 y 类

我希望能够在 x 中做一些事情,例如获取带有 ID 的文本视图并更改文本。 要做到这一点,我必须获得观点,但我遇到了问题。 我尝试过 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
    }
}

【问题讨论】:

  • 请添加一些代码来理解您的问题。

标签: java android android-studio android-lifecycle class-extensions


【解决方案1】:

我会将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,但您可以在执行任何操作之前检查它是否已定义(它不为空)。

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

public class x extends Activity {
    protected TextView myTextView;

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

        myTextView = findViewById(...);
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-01-23
    相关资源
    最近更新 更多