简体   繁体   English

如何从片段 Android 访问活动变量

[英]How to access Activity Variables from a fragment Android

In the Activity I have :在活动中我有:

public class tabsmain extends Activity{
    public static Context appContext;

    public boolean lf_ch=false;

    public void onCreate(Bundle savedInstanceState){

I would like to access and possibly change lf_ch from a fragment inside tabsmain;我想从 tabsmain 中的片段访问并可能更改 lf_ch;

public class tabquests extends Fragment{ 
    public CheckBox lc;
@Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)//onCreateView
    { 
lc.setChecked(//set it to lf_ch);

However, I can't seem to access the value of lf_ch.但是,我似乎无法访问 lf_ch 的值。

Try this:尝试这个:

public View onCreateView(...){
  tabsmain xxx = (tabsmain)getActivity();
  lc.setChecked(xxx.lf_ch);
}

I know this is an old question, however here is an easy answer that work without jumping through any hoops.我知道这是一个老问题,但是这里有一个简单的答案,无需跳过任何环节即可工作。 In you Fragment define a variable that is the Activity that the fragment will be in then in the onCreateView connect the variable to the activity and then you have a reference that can get to any public variable in the main activity.在您的片段中定义一个变量,该变量是片段所在的活动,然后在 onCreateView 中将变量连接到活动,然后您就有了一个可以访问主活动中任何公共变量的引用。 I had forgotten it when I ended up here.当我结束这里时,我已经忘记了。 It's a little hard to do the other way as you need to find the exact fragment that is showing.另一种方式有点困难,因为您需要找到正在显示的确切片段。 However with this you shouldn't need to do it the other way because you can easily pass things back and forth.但是,有了这个,您不需要以其他方式进行操作,因为您可以轻松地来回传递信息。 I hope this help anyone that comes across it.我希望这可以帮助任何遇到它的人。

public Quiz_Avtivity mainQuiz;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) {
ViewGroup rootView = (ViewGroup) inflater.inflate(R.layout.fragment_quiz, container, false);

mainQuiz = (Quiz_Avtivity) getActivity();
//Below is where you get a variable from the main activity
mainQuiz.AnyPublicVariable = whatEver;
//also
whatEver = mainQuiz.AnyPublicVariable

if you are using Java, you can use如果您使用的是 Java,则可以使用

((YourActivityName)getActivity()).variableName

to access, and if you are using Kotlin, you can use访问,如果您使用的是 Kotlin,则可以使用

(activity as YourActivityName).variableName

If the variable is defined as null in kotlin, you have to try each of these method as well:-如果变量在 kotlin 中定义为 null,则您还必须尝试以下每种方法:-

(activity as? YourActivityName).variableName

(activity as? YourActivityName)!!.variableName

or have to use let block, if possible.如果可能,或者必须使用 let 块。

Choose the correct one for you!选择适合您的一款!

Hope, It will help.希望,它会有所帮助。

take Activity value in fragment.取片段中的 Activity 值。

((MainActivity) getActivity()).mGoogleApiClient; ((MainActivity) getActivity()).mGoogleApiClient;

Make a generic Result receiver制作一个通用的 Result 接收器

在此处输入图片说明

You can create an interface for this task which would fetch a String data from any Activity to your Fragment.您可以为此任务创建一个接口,该接口将从任何活动中获取字符串数据到您的 Fragment。 Follow these steps.按着这些次序。

Create an interface创建接口

public interface MyResultReceiver{

      public String getResult();     

} 

Make MyResultReceiver a member of your Fragment使MyResultReceiver成为您的 Fragment 的成员

public class tabquests extends Fragment{ 

    public CheckBox lc;
    public MyResultReceiver resultreceiver;

    @Override
    public void onAttach(Context context){
         super.onAttach(cotext);
         resultreceiver = (MyResultReceiver)context;
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)//onCreateView
    { 

           YourFragment code code

           Boolean result = resultreceiver.getResult();
           lc.setChecked(result);

     }

}

Implement MyResultReceiver in the Activity and override the method在Activity中实现MyResultReceiver并覆盖方法

public class tabsmain extends Activity implements MyResultReceiver{

        public boolean lf_ch=false;

        // Activity code


        @Override
        public boolean getResult(){
             return lf_ch;
        }

 }

Disclaimer:免责声明:

You might find it a bit lengthy for this case.对于这种情况,您可能会发现它有点冗长。 But the plus point of this approach is that if you want to reuse this code for another activity.但是这种方法的优点是,如果您想将此代码重用于另一个活动。 You will not have to write the same logic again.您将不必再次编写相同的逻辑。 Just implement the MyResultReceiver in your activity , override the method and your will be good to go.只需在您的活动中实现MyResultReceiver ,覆盖该方法,您就可以开始了。

TIP: To be able to get any kind of data, change the method definition in the interface提示:为了能够获取任何类型的数据,更改接口中的方法定义
from public String getResult();public String getResult(); to public Object getResult();public Object getResult();

Another way to get data from activity is to access activity's intent via:从活动中获取数据的另一种方法是通过以下方式访问活动的意图:

getActivity.getIntent().getExtras();

and etc.等等。

It can be useful if you starts activity with fragment in xml, and would like to control somehow fragment's onCreate() behavior.如果您使用 xml 中的片段启动活动,并且想以某种方式控制片段的 onCreate() 行为,它会很有用。

PS: of cause you should firstly put something to intent PS:当然你应该首先把一些东西放在心上

您可以尝试以下方法:

lc.setChecked(((yourpackagename)getActivity()).lf_ch);

try tabsmain.appContext.lf_ch will give u value of that variable.试试tabsmain.appContext.lf_ch会给你那个变量的值。

Also in that activity set appContext = this同样在该活动中设置appContext = this

try this尝试这个

public boolean lf_ch=false;
public class tabsmain extends Activity{

    public static Context appContext;
    public void onCreate(Bundle savedInstanceState){

尝试这样的事情:

    ViewPager mViewPager = (ViewPager) getActivity().findViewById(R.id.m_view_pager);

Access Activity variables in fragment to use static keyword like this:访问片段中的活动变量以使用静态关键字,如下所示:

MainActvity.java主活动.java

public static boolean lf_ch=false;

tabquestsFragment.java tabquestsFragment.java

boolean if_value=MainActvity.lf_ch;

I hope it helps you我希望它能帮助你

note that your fragment loads before the activity.请注意,您的片段在活动之前加载。 so, you have to call the所以,你必须调用

tabsmain tabsm=(tabsmain) getActivity();

line in onActivityCreated() methodonActivityCreated()方法中的行

Solution : You can try this.解决方案:你可以试试这个。

In tabquests Fragment use this,在 tabquests 片段中使用这个,

public class tabquests extends Fragment{ 
    private tabsmain tabsmainActivity;
    public CheckBox lc;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup 
         container,Bundle savedInstanceState)//onCreateView
    { 
        tabsmainActivity = (tabsmain)getActivity; //typecasting 
        //now you can access the variables of tabsmain activity and make 
        //sure you give them public access in the activity`
        tabsmainActivity.lf_ch; //or do whatever operation you want here.
        lc.setChecked(//set it to lf_ch);
    }

Change: public boolean lf_ch=false;更改: public boolean lf_ch=false; to: public static boolean lf_ch=false;到: public static boolean lf_ch=false; You can access/change the value with: tabsmain.lf_ch您可以访问/更改值: tabsmain.lf_ch

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM