我有一个包含多个选项卡的 Activity (使用“固定选项卡+滑动”样式)。每个选项卡布局都定义为一个 fragment xml 文件。
例如,我的 Activity 称为 ModifyCustActivity
。这使用了一个几乎为空的 xml 文件,名为 activity_modify_cust.xml
。此页面上的每个选项卡都由各种 xml 文件表示,例如 fragment_modify_cust_basic
和 fragment_modify_cust_address
等。每个 fragment xml 文件都包含 EditText
, Spinner
等等。
当 Activity 开始时,我需要能够从 Activity 代码访问这些 View ,因为我需要预先填充它们,并在编辑后获取它们的结果。但是,因为这些 View 存在于 fragment xml 文件中,所以我似乎无法在代码中访问它们。有没有办法访问 fragment xml 文件中包含的 View ?
最佳答案
Is there a way to access a view contained in a fragment xml file?
是的,但是您的 fragment 应该在 XML 布局文件中声明,这似乎是您的情况。
例如:
<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>
您将像这样访问 fragment :
FragmentManager manager = getSupportFragmentManager();
MyFragment fragment = (MyFragment)manager.findFragmentById(R.id.my_fragment);
然后使用 fragment
实例,您可以进一步访问您的 View ,例如通过从更新某些特定 View 的 fragment 调用公共(public)方法。
更新:
假设您有一个出现在 fragment 布局中的 TextView
,并且需要从 Activity 进行更新。
让它成为 fragment 类:
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);
}
}
然后,您可以通过在 Activity 中调用 updateTextView()
方法来更新 TextView
:
fragment.updateTextView("text");
关于android - 使用 fragment xml 文件中的 View ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17994077/