简体   繁体   English

片段设置值的 onCreateview 为全局变量返回空值?

[英]onCreateview of fragment set value to Global variable return null value?

i am stuck within a fragment.below is my fragment code我被困在一个片段中。下面是我的片段代码

public class Tab1 extends Fragment {
    EditText address,contactNumber,dob;
    String adds;

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

        View v =inflater.inflate(R.layout.tab_1,container,false);

        contactNumber= (EditText)v.findViewById(R.id.editTextcontact);
        address= (EditText)v.findViewById(R.id.editText2);
        dob= (EditText) v.findViewById(R.id.editText3);

        contactNumber.setHint("Your ContactNo Plz");
        address.setHint("Your address Plz");
        dob.setHint("Your Data Of Birth");
//receive data from main activity
        TabedActivity activity = (TabedActivity) getActivity();
        String myDataFromActivity = activity.getMyData();
//
       adds=address.getText().toString();

        return v;
    }

    public String getData(){
      return adds;
    }
}

what i want is when this fragment is called from the main activity the text in the edittext should pass to the adds variable.i check it like above but it show me a null value.how could i set this value.?please help我想要的是当从主要活动调用这个片段时,edittext 中的文本应该传递给 adds 变量。我像上面一样检查它,但它显示一个空值。我怎么能设置这个值。?请帮忙

You need return address.getText().toString() and check for null;您需要返回 address.getText().toString() 并检查是否为空;

Sample:样本:

public String getData(){
      if(address != null && address.getText() != null) 
      return address.getText().toString(); 
      return null; // block NPE
    }

In onCreateView you do:在 onCreateView 你做:

address= (EditText)v.findViewById(R.id.editText2);

and in the same event you then do:在同一事件中,您会执行以下操作:

adds=address.getText().toString();

but offcourse the user at this point didn't set its value yet.但是此时用户还没有设置它的值。

That said, it's also important to check when in your activity are you trying to get this value.也就是说,检查您在活动中何时尝试获取此值也很重要。

You should pass your desired data to fragment from your parent activity while creating fragment.在创建片段时,您应该将所需的数据从父活动传递到片段。 Sample code can be like below示例代码如下

 Bundle args = new Bundle();
    args.putString("address", address);
    fragment.setArguments(args);

Now in your fragment get the value back like现在在你的片段中得到像

getArguments().getString("address");

Hope it helps.希望能帮助到你。

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

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