2

膨胀我有一个FragmentActivity其中设置与3个标签的主布局。每个选项卡都有自己的片段,这些片段是自己的主布局布局。如何设置数据到布局由一个片段

例如,三个片段之一:

public class Fragment1 extends Fragment { 

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

当我添加的所有片段,并连接它们与标签一切正常。当我点击tab1时,Fragment1的布局显示,当我点击Tab2时,Fragment2的布局显示。

问题是,当我想改变该膨胀的布局中的东西(例如在fragment1布局中执行setText到textView)时,我在该行中收到一个NullPointerException,并且应用程序停止。

这不起作用:

TextView test = (TextView) findViewById(R.id.fragmentOneText1); 
test.setText("Test text!"); 

如何数据集虚增布局?

回答

3

你必须使用LayoutInflater第一虚增您的具体片段的布局,并在您的片段映射控制

@Override 
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { 

     View fragmentView = inflater.inflate(R.layout.R.layout.fragment1, container, false); 
     TextView text = (TextView) fragmentView.findViewById(R.id.fragmentOneText1); 
     mTextNoResult=(TextView)fragmentView.findViewById(R.id.text_noresult); 
     return fragmentView; 
} 
+0

能否请你解释这一点呢?我不明白这与LayoutInflater。我需要在哪里使用它? – Cristiano

+0

用我的代码替换你的'onCreateView()',LayoutInflater会将特定的布局(fragment1)膨胀到你的Fragment。 –

+0

它的工作原理!我只想问你一个问题。如何将数据从FragmentActivity传输到Fragment?在FragmentActivity中生成的结果需要在该膨胀的布局中显示。谢谢! – Cristiano

相关问题