简体   繁体   English

从 MainActivity 在 Fragment 中编辑 EditText

[英]Edit EditText in Fragment from MainActivity

I've tried to replace textviews whose are connected to fragment with data that I get from service.我试图用我从服务中获得的数据替换连接到片段的文本视图。 But even if I use LayoutInflator in Activity to edit those edittextes, I couldn't change them.但即使我在 Activity 中使用 LayoutInflator 来编辑这些编辑文本,我也无法更改它们。 All I understand is that I need to change them from the fragment but I need to send data from activity to fragment for that, which I couldn't achieve again.我所了解的是,我需要从片段中更改它们,但我需要为此将数据从活动发送到片段,而我无法再次实现。

Here's the code lines that I wrote inside onCreate of MainActivity这是我在MainActivity 的onCreate中写的代码行

        LayoutInflater layoutInflater = (LayoutInflater) getApplicationContext()
                .getSystemService(Context.LAYOUT_INFLATER_SERVICE);

        View mView = layoutInflater.inflate(R.layout.tab_designreservation, null);

        Bundle extrasofuser = getIntent().getExtras();
        nameofuser = extrasofuser.getString("nameofuser").toString();
        surnameofuser = extrasofuser.getString("surnameofuser").toString();

        EditText enum_of_name = (EditText) mView.findViewById(R.id.et_name);
        EditText enum_of_surname = (EditText) mView.findViewById(R.id.et_surname);

        enum_of_name.setText(nameofuser);
        enum_of_surname.setText(surnameofuser);

As far as I know, I need to send those string variables to fragment but I couldn't do it.据我所知,我需要将这些字符串变量发送到片段,但我做不到。 Thanks for your helps!!谢谢你的帮助!!

If I understood well your problem, you need to set the text of a editText in a Fragment from your Activity.如果我理解你的问题,你需要在你的活动的片段中设置一个 editText 的文本。 An approach is to keep a reference of the fragment in your activity.一种方法是在您的活动中保留片段的引用。

     private MyFragment mFragment;

     @Override
     protected void onCreate(Bundle savedInstanceState) {
        ...
        mFragment = new MyFragment();
        ...
     }

And then create a method in your fragment class to change the EditText text:然后在您的片段类中创建一个方法来更改 EditText 文本:

     public void changeEditTextContent(Bundle extras){
          String nameofuser = extrasofuser.getString("nameofuser").toString();
          String surnameofuser = extrasofuser.getString("surnameofuser").toString();

           EditText enum_of_name = (EditText) rootView.findViewById(R.id.et_name);
           EditText enum_of_surname = (EditText) rootView.findViewById(R.id.et_surname);

           enum_of_name.setText(nameofuser);
           enum_of_surname.setText(surnameofuser);
     }

Lastly, from your activity you can call this method:最后,您可以从您的活动中调用此方法:

     Bundle extrasofuser = getIntent().getExtras();
     mFragment.changeEditTextContent(extrasofuser);

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

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