簡體   English   中英

如何在片段中的方法中增加布局

[英]How to inflate a layout in method in 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.
    }

如何解決這個問題? 因為在活動中,我們只可以在方法中最終結束TextView df =(TextView)findViewById(R.id.df)即可。

您必須在您的片段中創建一個全局View promptView

您的代碼應如下所示:

private View promptView = null;

public View onCreateView(LayoutInflater inflater, ViewGroup container, 
Bundle savedInstanceState) {
    if(promptView == null){
       promptView = inflater.inflate(R.layout.fragment_messages, container, false);

       sendRestoreRequest2();
    }
    return promptView;
}


public void sendRestoreRequest2() {
    final TextView df=(TextView)promptView.findViewById(R.id.df);
}

嘗試這個:

public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
   View promptView = inflater.inflate(R.layout.fragment_messages, container, false);
   sendRestoreRequest2(promptView);
   return promptView;
}

public void sendRestoreRequest2(View promptView) {
   final TextView df = (TextView) promptView.findViewById(R.id.df);
}

您在ONCREATEVIEW范圍之外的方法中沒有膨脹的PromptView的范圍

你可以做的一件事就是這樣

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);
    }

解決方案二是這樣的

您可以通過覆蓋Fragment類中的OnActivityCreated方法來使用簡單的getActivty()。findViewbyId來在fragment類中執行findViewbybyid(盡管這是一種被動方法)

對不起,每個人我都是新手。我剛剛找到了解決方案

放在inoncreateview上。 從最終的TextView更改為df =(TextView)promptView.findViewById(R.id.df); 到df = view.findViewById(R.id.df);

而且有效。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM