Android 如何在 Fragment 中访问父活动视图

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/22883599/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-20 06:31:27  来源:igfitidea点击:

How to access parent Activity View in Fragment

androidandroid-fragmentsfragment

提问by Bot

I have an ActionBarActivityand fragment. I am using FragmentPagerAdapterthat provides fragment to my app. My question How can I access parent Activity View in Fragment ??

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

回答by Raghunandan

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

具体来说,fragment 可以通过 getActivity() 访问 Activity 实例,并轻松执行诸如在 Activity 布局中查找视图等任务

回答by Mohsen mokhtari

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
}

回答by kishan verma

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

在 Kotlin 中,很容易在 Fragment 中访问父活动视图

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

回答by Irfandi D. Vendy

Note that if you are using findViewById<>() from activity, it wont work if you call it from fragment. You need to assign the view to variable. Here is my case

请注意,如果您从活动中使用 findViewById<>() ,如果您从片段中调用它,它将无法工作。您需要将视图分配给变量。这是我的情况

This doesn't work

这不起作用

class MainActivity{

    fun onCreate(...){
        //works
        setMyText("Set from mainActivity")
    }

    fun setMyText(s: String){
        findViewById<TextView>(R.id.myText).text = s
    }
}
________________________________________________________________

class ProfileFragment{
    ...

    fun fetchData(){
        // doesn't work
        (activity as MainActivity).setMyText("Set from profileFragment")
    }
}

This works

这有效

class MainActivity{

    private lateinit var myText: TextView

    fun onCreate(...){
        myText = findViewById(R.id.myText)

        // works
        setMyText("Set from mainActivity")
    }

    fun setMyText(s: String){
        myText.text = s
    }
}
________________________________________________________________

class ProfileFragment{
    ...

    fun fetchData(){
        // works
        (activity as MainActivity).setMyText("Set from profileFragment")
    }
}