android - 使用 fragment xml 文件中的 View

标签 android android-fragments

我有一个包含多个选项卡的 Activity (使用“固定选项卡+滑动”样式)。每个选项卡布局都定义为一个 fragment xml 文件。

例如,我的 Activity 称为 ModifyCustActivity。这使用了一个几乎为空的 xml 文件,名为 activity_modify_cust.xml。此页面上的每个选项卡都由各种 xml 文件表示,例如 fragment_modify_cust_basicfragment_modify_cust_address 等。每个 fragment xml 文件都包含 EditTextSpinner 等等。

当 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/

相关文章:

Android fragment 在 iOS 的 swift 中模拟

android - 如何在 fragment 中实现 ImageView 的 OnClickListener?

java - 使用 Android Google Maps API 设置 MapType 空指针异常

android - 如何动态交换 fragment ?

android - 通过日历对象设置闹钟

android - 违反 Google Play 开发者政策的警告 : Action Required

android - 如何从 Android 上的 Firebase 存储下载图像?

Android:批量插入,当 InsertHelper 被弃用时

javascript - 如何阻止 YouTube 使用内置浏览器?

android - fragment 中奇怪的 onPause()、onResume() 行为