android - 在 fragment 中获取对 LinearLayout 的引用

标签 android fragment

在我的布局的 XML 文件中,我添加了一个 fragment 。 我的 fragment 的布局是一个 LinearLayout,它包含一个 TextView 。

我想在我的 fragment 类中获得对 LinearLayout 对象的引用,但尽管尝试了我能想到或在网上找到的所有方法,它始终为 null。

@Override
public void onActivityCreated(Bundle savedInstanceState) {
    super.onActivityCreated(savedInstanceState);

    text = (TextView) getActivity().findViewById(R.id.text);
    layout = (LinearLayout) getActivity().findViewById(R.id.layout);

    if(layout == null){
        text.setText("null");
    }
}

这段代码在我的 fragment 类中,导致 TextView 的文本被设置为“null”,因为布局为 null。这怎么可能,因为我试图以完全相同的方式获取对布局和 TextView 的引用?


在 Activity 类中创建

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_test);

    manager = getFragmentManager();
    MyFragment = (MyFragment) manager.findFragmentById(R.id.fragment);

}

方法二

我尝试在我的 Activity 中获取对 LinearLayout 的引用。这是此 Activity 的 onCreate 尝试。

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_test);

    manager = getFragmentManager();
    MyFragment = (MyFragment) manager.findFragmentById(R.id.fragment);

    LinearLayout ll = (LinearLayout) findViewById(R.id.layout);
    TextView tv = (TextView) findViewById(R.id.text);

    if(ll == null){
        tv.setText("null");
    }
}

这也将文本更改为“null”。

最佳答案

通过在 fragment 类中声明 layout = (LinearLayout) getView() 或在 fragment 类中声明 layout = (LinearLayout) fragment.getView() 可以解决这两种情况 Activity 。这并没有回答为什么我所做的不起作用(这可能会有所帮助),但这解决了问题。

关于android - 在 fragment 中获取对 LinearLayout 的引用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38190889/

相关文章:

android - 不能垂直居中按钮

android - 添加 firebase 后,所有 com.android.support 库必须使用完全相同的版本规范

android - 具有静态引用的 Activity

android - 是否可以通过编程方式/从终端设置 pin 码和指纹?

Android Fragments 不更新

android - 在 RecyclerView 的 ViewHolder 上不显示 getSupportFragmentManager

android - 在 Fragment 中使用 GridView 和 ArrayAdapter<String>

java - 我正确地初始化了 fragment ,但它在交易后没有出现

android - 如何使用 ADB 识别安卓模拟器 (AVD)

jsf - 定义<ui :fragment> tag in jsf有什么用