【问题标题】:How to pass values from Fragment to Activity如何将值从 Fragment 传递到 Activity
【发布时间】:2021-04-10 17:01:04
【问题描述】:

我是 Android 开发的新手。我正在尝试将值从片段传递到活动,但经过多次尝试后我无法得到答案......

这是我的片段:

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;
}

这是我要传递值的类

【问题讨论】:

  • 您的问题似乎不完整
  • 如果是的话,代码会给你一个错误,给我们看看

标签: android android-fragments


【解决方案1】:

你应该在你的片段中创建一个接口并且你应该实现你的 Activity 类的接口。

例如,在您的 Fragment 中:

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
    }
}

更多信息可以查看the offical documentation

【讨论】:

  • onAttach(Activity activity) : 现已弃用。
  • 是的,onAttach(上下文上下文)更有意义。
【解决方案2】:

这是我使用的解决方案,这可行,但不是一个好习惯

在你的活动中为你想要传递的数据编写getter和setter,例如如果你想传递一个字符串名称写

  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();

【讨论】:

    【解决方案3】:

    对于可能在某个时候来这里的人,请注意此线程中的答案已过时。 Fragment 库现在提供了两个通信选项:共享 ViewModel 和 Fragment Result API。请参考官方文档here

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-11-12
      • 2018-11-20
      • 1970-01-01
      • 1970-01-01
      • 2019-05-26
      • 1970-01-01
      相关资源
      最近更新 更多