Rob*_*obT 14 android dynamic textview android-fragments
我正在尝试使用片段来构建我的第一个正确的Android应用程序.我有一个主要的xml.它由两个垂直片段组成,顶部片段只包含两个TextView.第一个包含静态文本,第二个包含一个值,我最终将从SQL动态获取.
如果我把它作为我的MainActivity.java,那么它很高兴在我的第一个片段中更新TextView的值:
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Set the Text to try this out
TextView t = (TextView)findViewById(R.id.viewItem);
t.setText("Text to Display");
}
Run Code Online (Sandbox Code Playgroud)
我有两个片段XML和一个java来支持每个,所以我想把这个字段的设置放到支持片段的Java而不是MainActivity的java.
当我把它放在片段中它看起来像这样: -
public class FragmentMainTop extends Fragment {
@Override
public View onCreateView(LayoutInflater inflater,
ViewGroup container, Bundle savedInstanceState){
// -- inflate the layout for this fragment
return inflater.inflate(R.layout.fragmentmt, container,false);
// Set the Text to try this out
TextView t = (TextView)findViewById(R.id.viewItem);
t.setText("Text to Display");
}
Run Code Online (Sandbox Code Playgroud)
但是如果我这样做,我会在TextView行上出错:
"对于FragmentMainTop类型,方法findViewById(int)是未定义的"
那么为什么它不知道这种方法呢?我有ctl/shift/o所以我知道我有所有正确的进口.我不想最终将所有代码放在MainActivity中,因为如果我想在另一个活动中使用Fragment,我将不得不重复所有代码.
Tyl*_*ell 47
您需要将膨胀的片段布局分配给变量,以便您可以访问其findViewById()方法.然后在完成更新小部件后返回它.
@Override
public View onCreateView(LayoutInflater inflater,
ViewGroup container, Bundle savedInstanceState){
// -- inflate the layout for this fragment
View myInflatedView = inflater.inflate(R.layout.fragmentmt, container,false);
// Set the Text to try this out
TextView t = (TextView) myInflatedView.findViewById(R.id.viewItem);
t.setText("Text to Display");
return myInflatedView;
}
Run Code Online (Sandbox Code Playgroud)
通常,当你findViewById()在一个内部打电话时Activity,你正在调用Activity.findViewById().在Fragment类中尝试相同的调用将失败,因为没有这样的Fragment.findViewById()方法.因此,您必须使用View.findViewById()膨胀的视图来获取对小部件的引用.
| 归档时间: |
|
| 查看次数: |
36759 次 |
| 最近记录: |