java - 如何在 fragment 的方法中膨胀布局

标签 java android

实际上我有一个 fragment 。`

public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    // Inflate the layout for this fragment
    View promptView = inflater.inflate(R.layout.fragment_messages, container, false);

    sendRestoreRequest2();

    return promptView;
}


public void sendRestoreRequest2() {

     final TextView df=(TextView)promptView.findViewById(R.id.df);//this will give an error. I dont know how to inflate this one because this is a fragment.
    }

如何解决这个问题?因为在 Activity 中我们只需在方法中调用 Final TextView df=(TextView)findViewById(R.id.df) 即可。

最佳答案

在 ONCREATEVIEW 范围之外的方法中不具有膨胀的 PromptView 范围

one thing that you can do is like this

public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    // Inflate the layout for this fragment
    View promptView = inflater.inflate(R.layout.fragment_messages, container, false);

    sendRestoreRequest2(promptView);

    return promptView;
}


public void sendRestoreRequest2(View incomingPromptView) {
     // here now you have that promptView in your other method's scope and this should register the TextView in your Fragment
     final TextView df=(TextView)incomingPromptView.findViewById(R.id.df);
    }

Solution number Two is like this

您可以通过使用简单的 getActivty().findViewbyId 在 Fragment 类中覆盖 OnActivityCreated 方法来在 Fragment 类中执行 findViewbyid (但这是一种被动方法)

关于java - 如何在 fragment 的方法中膨胀布局,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53221485/

相关文章:

java - Hamcrest assertThat 模棱两可?

java - 在代码中解密 AES 加密的授权 token 方法时 Jar 崩溃。 hs_err _pid 文件提到 arrayof_jbyte_fill

java - 如何停止覆盖数组列表?

java - 当我点击java按钮时什么也没有发生

java - android中的数独解决方案检查

java - 如何从相机 Intent 获取 URI?

android - Android延长声音 fragment

java - Spring Hibernate-JPA 使用基于 Java 的配置 org.springframework.beans.factory.NoSuchBeanDefinitionException

android - Phonegap Dev App 未出现在 chrome 远程调试器中

android - 通知声音有问题