1

I have read the artical How to pass and get value from fragment and activity android kotlin

I have to pass a var mClipboardManager (see Code A) in a activity to Fragment.

How can I pass the var ? and how get the var in Fragment?

Code A

   private lateinit var mClipboardManager: ClipboardManager 

    private val aPrimaryClipChangedListener = ClipboardManager.OnPrimaryClipChangedListener {
        if (mClipboardManager.hasPrimaryClip() && mClipboardManager.primaryClipDescription.hasMimeType(ClipDescription.MIMETYPE_TEXT_PLAIN) ) {
            var pasteData: String = ""
            val item = mClipboardManager.primaryClip.getItemAt(0)
            pasteData = item.text.toString().trim()
            addClipboardRecord(pasteData)
        }
    }
HelloCW
  • 843
  • 22
  • 125
  • 310
  • Do you really need to pass it? Can't you just `getSystemService()` in the `Fragment`? It's the same system service everywhere. – Mike M. Dec 10 '18 at 03:14
  • 1
    You really don't. `Fragment` has access to a `Context` as soon as it's attached, and that's all you need to get a system service. Why can't you get the `ClipboardManager` in the `Fragment`? – Mike M. Dec 10 '18 at 03:41

1 Answers1

1

You don't need to pass, you can get this in your fragment, but anw, you can pass mClipboardManager from your activity into you fragment by 2 way

1. Set value from your activity.

First, get fragment instance using getFragmentManager().findFragmentByTag("YourFragmentTag")

in your fragment, create a method

public void setClipboardManager(ClipboardManager clipboardManager) {
  // here you get an instance of clipboardManager, do anything you want
}

and call this method in your activity:

fragment.setClipboardManager(mClipboardManager)

2. Get the value of mClipboardManager from you fragment

First, create a method in your activity

public ClipboardManager getClipboardManager() {
   return mClipboardManager;
}

then, in

@Override public void onAttach(Context context) {
        super.onAttach(context);
        if (getActivity() instanceof YourActivity) {
            ((YourAcitivity) getActivity()).getClipboardManager()
            // here you get an instance of clipboardManger, do anything you want
        }
    }
GianhTran
  • 3,443
  • 2
  • 22
  • 42