如何在片段中访问父活动视图[英] How to access parent Activity View in Fragment

本文是小编为大家收集整理的关于如何在片段中访问父活动视图的处理/解决方法,可以参考本文帮助大家快速定位并解决问题,中文翻译不准确的可切换到English标签页查看源文。

问题描述

我有一个ActionBarActivity和碎片.我正在使用FragmentPagerAdapter为我的应用提供片段.我的问题如何访问片段中的父活动视图?

推荐答案

您可以使用

View view = getActivity().findViewById(R.id.viewid);

引用文档

具体来说,片段可以使用 getActivity()并轻松执行任务,例如在 活动布局

其他推荐答案

kotlin中,在片段中访问父活动视图非常容易

activity!!.textview.setText("String")

其他推荐答案

首先,创建一个这样的视图:

View view = getActivity().findViewById(R.id.viewid);

然后将其转换为您需要这样需要的任何视图:

 if( view instanceof EditText ) {
            editText = (EditText) view;
            editText.setText("edittext");
            //Do your stuff
        }

if( view instanceof TextView ) {
  TextView textView = (TextView) view;
  //Do your stuff
}

本文地址:https://www.itbaoku.cn/post/2091030.html

问题描述

I have an ActionBarActivity and fragment. I am using FragmentPagerAdapter that provides fragment to my app. My question How can I access parent Activity View in Fragment ??

推荐答案

You can use

View view = getActivity().findViewById(R.id.viewid);

Quoting docs

Specifically, the fragment can access the Activity instance with getActivity() and easily perform tasks such as find a view in the activity layout

其他推荐答案

In Kotlin it is very easy to access parent Activity View in Fragment

activity!!.textview.setText("String")

其他推荐答案

At first, create a view like this:

View view = getActivity().findViewById(R.id.viewid);

Then convert it to any view that you need like this:

 if( view instanceof EditText ) {
            editText = (EditText) view;
            editText.setText("edittext");
            //Do your stuff
        }

or

if( view instanceof TextView ) {
  TextView textView = (TextView) view;
  //Do your stuff
}