我有一个片段活动我需要将Text设置为该Activity中的文本视图,当我使用以下代码获取空指针异常时。 可以使用任何其他方法来设置文本视图的数据。
public class Introduction extends Fragment {
TextView txt;
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View v= inflater.inflate(R.layout.activity_introduction, container, false);
txt=(TextView) v.findViewById(R.id.officeheader);
return v;
}
public void setText(String text){
txt.setText(text);
}
}
并在My Fragment Activity类中:
frgManager=getSupportFragmentManager();
frgManager.beginTransaction()
. replace(R.id.fragmentoffice, introduction,"introduction")
.commit();
introduction.setText(" Office Coffee that will \n have everyone talking ");
答案 0 :(得分:2)
在包中设置字符串
Bundle bundl = new Bundle();
bundl.putString("Text", text);
introduction.setArguments(bundl)
frgManager=getSupportFragmentManager();
frgManager.beginTransaction()
. replace(R.id.fragmentoffice, introduction,"introduction")
.commit();
从包中获取文字
public class Introduction extends Fragment {
TextView txt;
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
String str = getArguments().getString("Text");
View v= inflater.inflate(R.layout.activity_introduction, container, false);
txt=(TextView) v.findViewById(R.id.officeheader);
setText(str);
return v;
}
public void setText(String text){
txt.setText(text);
}
}
答案 1 :(得分:-1)
你可以编写介绍构造函数,其中包含一个参数Type String, 在onCreateView上,您可以初始化textivew和settext