如何将值从Fragment传递给Activity

时间:2017-01-02 13:26:31

标签: android android-fragments

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

这是我的片段:

Error: Redis connection to 127.0.0.1:6379 failed - connect ECONNREFUSED 127.0.0.1:6379
    at Object.exports._errnoException (util.js:907:11)
    at exports._exceptionWithHostPort (util.js:930:20)
    at TCPConnectWrap.afterConnect [as oncomplete] (net.js:1078:14)

这是我要传递值的类

3 个答案:

答案 0 :(得分:2)

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

例如,在你的片段中:

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

答案 1 :(得分:0)

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

在您的活动中为您要传递的数据编写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();

答案 2 :(得分:0)

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