如何从Fragment传递值到Activity

3

我是一名Android开发新手,我正在尝试从Fragment传递值到Activity,但是经过多次尝试后,我仍然无法得到答案...

这是我的Fragment代码:

public OtpGentation(int OTP)
{
    this.OTP =OTP;
}
public OtpGentation(String number1, String email1, String password)
{
    number = number1;
    mail = email1;
    pass = password;
}

public OtpGentation() {


}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
    rootview = inflater.inflate(R.layout.otp, container, false);
    Bundle bundle = getArguments();

    new OTPAsyncManager().execute();

    etxotp =(EditText)rootview.findViewById(R.id.etxotp);
    btnNext = (Button) rootview.findViewById(R.id.nextToOTP);
    btnCancel =(Button) rootview.findViewById(R.id.cancel);

    //etxotp.setText(OTP);
    btnNext.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view)
        {

            if (etxotp.getText().toString().equals(""))
            {
                Toast.makeText(getContext(), "Please Enter OTP ", Toast.LENGTH_SHORT).show();

            }
            else
            {
                int enteredOtp = Integer.parseInt(etxotp.getText().toString());
                if (enteredOtp ==OTP)
                {

                    Toast.makeText(getContext(), "OTP Matched", Toast.LENGTH_SHORT).show();
                    Bundle bun = new Bundle();
                    bun.putString("no",number);
                    bun.putString("ma",mail);
                    bun.putString("pa",pass);
                    Intent subintent = new Intent(getContext(),SubmitRegistration.class);
                    subintent.putExtras(bun);
                    startActivity(subintent);



                }
                else
                {
                    Toast.makeText(getContext(), "Please Enter Correct OTP ", Toast.LENGTH_SHORT).show();
                }

            }


        }
    });
    btnCancel.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view)
        {

            fragmentManager = getActivity().getSupportFragmentManager();
            HomeScreen fragmentOne = new HomeScreen();

            fragmentManager
                    .beginTransaction()
                    .setCustomAnimations(android.R.anim.slide_in_left, android.R.anim.slide_out_right)
                    .replace(R.id.content_frame, fragmentOne)
                    .addToBackStack("")
                    .commit();

        }
    });


    return rootview;
}

这是我想要传递值的类


看起来你的问题不完整。 - Manza
如果这段代码出现了错误,请告诉我们。 - Dasser Basyouni
3个回答

2

你应该在你的碎片中创建一个接口,然后实现该接口到你的活动类中。

例如,在你的碎片中:

OnHeadlineSelectedListener mCallback;

    // Container Activity must implement this interface
    public interface OnHeadlineSelectedListener {
        public void onArticleSelected(int position);
    }

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);

        // This makes sure that the container activity has implemented
        // the callback interface. If not, it throws an exception
        try {
            mCallback = (OnHeadlineSelectedListener) activity;
        } catch (ClassCastException e) {
            throw new ClassCastException(activity.toString()
                    + " must implement OnHeadlineSelectedListener");
        }
    }

你可以像这样发送任何值:

        // Send the event to the host activity
        mCallback.onArticleSelected(position);

你的活动应该是这样的:

public static class MainActivity extends Activity
        implements HeadlinesFragment.OnHeadlineSelectedListener{
    ...

    public void onArticleSelected(int position) {
        // The user selected the headline of an article from the HeadlinesFragment
        // Do something here to display that article
    }
}

想要了解更多信息,可以查看官方文档


onAttach(Activity activity):现在已经被弃用。 - Ronak Poriya
1
是的,onAttach(Context context)更有意义。 - ziLk

0

对于可能会在这里查找答案的人,请注意本帖中的答案已经过时。现在Fragment库提供了两种通信选项:共享ViewModel和Fragment Result API。请参考官方文档此处


0

这是我使用的解决方案,它可以工作,但不是一个好的实践。

在您的活动中编写获取器和设置器以传递数据,例如,如果您想要传递一个字符串名称,请编写:

  String   fileName;

 public String getFileName() {
    return fileName;
}
public void setFileName(String fileName) {
    this.fileName = fileName;
}

在你的片段中

public class YourFragment extends Fragment {

    Context contextCheckClass;
    private String fileName;



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

    View group=(View)inflater.inflate(R.layout.fragment_highlight, null);

         fileName=((MainActivity) getActivity()).setFileName("Your String to pass to activity");    //set what ever string you want to pass

    return group;
}

 }

如果您这样做,您将无法在MainActivity以外的任何其他位置使用此片段

如果您想从不同的活动访问相同的片段,则

在片段中创建一个传递上下文的构造函数。您会注意到它会发出有关避免非默认构造函数的警告,只需忽略它或禁用检查即可。

   public class YourFragment extends Fragment {

    private String fileName;
    Context contextCheckClass;

    public YourFragment (Context ctx) {
        this.contextCheckClass=ctx;
    }

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

    View group=(View)inflater.inflate(R.layout.fragment_highlight, null);
    if(contextCheckClass instanceof MainActivity){ //write your Activity name here
        //This fragment is called from MainActivity
         fileName=((MainActivity) getActivity()).getFileName(); 

        }
        else {
        //This fragment is called from some other activity
         }

    return group;
}

要加载此片段,请将活动上下文传递给它

 YourFragment yourFragment =new YourFragment (MainActivity.this);
 getSupportFragmentManager()
.beginTransaction()
.add(R.id.LL_Fragment, yourFragment)
.addToBackStack(null)
.commit();

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接