accessing textview within a fragment in activity

旧时模样 提交于 2019-12-03 16:03:32

You should call getView() on the Fragment and then use findViewById() on the view returned.

Of course, it won't return anything until after the view has been created, so you may have to call it somewhere besides onCreate.

Well, you need to inflate an xml file, or create one from scratch, though I wouldn't recommend it, unless you like the extra work :) But with an Activity, the setContentView() inflates your xml file, and subsequently in onCreate() you can access it the way you are use to. Mind you, if you try accessing a layout View outside of onCreate without the parent View, you will be getting the same issue. Unless you made a global variable. Since onCreate is where a developer will usually always start things off, Android made it easy to just omit the parent View from the findViewById.

Assuming you have an xml file called edit.xml:

public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
//this method is found within your Fragment, which you must ovverride
View view = inflater.inflate(R.layout.edit, container, false);
private EditText editText = (EditText) view.findViewById(R.id.editTextName);
//...
}

Feel free to check out the Android docs on Fragments to get a better understanding of why I chose to do it in that method instead of the Fragments onCreate, etc.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!