使用片段xml文件中的视图 [英] Use view from fragment xml file
问题描述
我有一个带有多个标签的活动(使用固定标签+滑动"样式).每个选项卡的布局都定义为片段xml文件.
I have an activity with several tabs (using the 'fixed tabs + swipe' style). Each tab layout is defined as a fragment xml file.
例如,我的活动称为 ModifyCustActivity
.这将使用一个几乎为空的xml文件,称为 activity_modify_cust.xml
.此页面上的每个标签都由各种xml文件表示,例如 fragment_modify_cust_basic
和 fragment_modify_cust_address
等.这些片段xml文件每个都包含 EditText
Spinner
s以及更多.
Eg, my activity is called ModifyCustActivity
. This uses an almost-empty xml file called activity_modify_cust.xml
. Each tab on this page is represented by various xml files such as fragment_modify_cust_basic
and fragment_modify_cust_address
etc etc. Each of these fragment xml files contains EditText
s, Spinner
s and more.
活动开始时,我需要能够从活动代码访问这些视图,因为我需要预先填充它们,并在对其进行编辑后获得其结果.但是,由于这些视图存在于片段xml文件中,因此我似乎无法通过代码访问它们.有没有办法访问片段xml文件中包含的视图?
When the activity starts, I need to be able to access these views from the activity code, as I need to pre-populate them, and get their results once they are edited. However, because these views exist in a fragment xml file, I don't seem to be able to reach them in code. Is there a way to access a view contained in a fragment xml file?
推荐答案
是否可以访问片段xml文件中包含的视图?
Is there a way to access a view contained in a fragment xml file?
是的,但是您的片段应该在XML布局文件中声明,这似乎是您的情况.
Yes it is, but your fragment should be declared in the XML layout file, which seems to be your case.
例如:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
...">
<fragment
android:name="com.example.MyFragment"
android:id="@+id/my_fragment"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
</LinearLayout>
您将像这样访问片段:
FragmentManager manager = getSupportFragmentManager();
MyFragment fragment = (MyFragment)manager.findFragmentById(R.id.my_fragment);
然后使用 fragment
实例,您可以进一步访问视图,例如,通过从片段中调用公共方法来更新某些特定视图.
Then using the fragment
instance you could further access your views, for example by calling a public method from the fragment which updates some particular view.
更新:
假设您有一个 TextView
出现在片段的布局中,并且需要从活动中进行更新.
UPDATE:
Suppose you have a TextView
that appears in layout of the fragment, and need to update from the activity.
让它成为片段类:
public class MyFragment extends Fragment{
private TextView textView;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_layout, null, false);
textView = (TextView)view.findViewById(R.id.textView);
return view;
}
public void updateTextView(String text){
textView.setText(text);
}
}
然后,您将通过在活动中调用 updateTextView()
方法来更新 TextView
:
Then you would update the TextView
by calling in your activity the updateTextView()
method:
fragment.updateTextView("text");
这篇关于使用片段xml文件中的视图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!