简体   繁体   中英

Fragment View is null when try to access from Activity

I have created a Fragment which is in ViewPager. Fragment is loading fine. I am using a button to swipe fragments in viewpager and before swiping, I want to check validations. So I did this in Activity :

val pos: Int = viewPager.currentItem
            val activeFragment: Fragment? = mAdapter.getItem(pos)
            if (viewPager.currentItem == 0) {

                if (pos == 0) (activeFragment as FragmentOne).checkValidation()

Below is my Fragment code.

class FragmentOne: BaseFragment() {

        fun newInstance(): FragmentOne{
            val args = Bundle()
            val fragment = FragmentOne()
            fragment.setArguments(args)
            return fragment
        }


        override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?,
                                  savedInstanceState: Bundle?): View? {
            val view : View = inflater.inflate(R.layout.fragment_one, container, false);
            return view
        }

        override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
            super.onViewCreated(view, savedInstanceState)
        }

        override fun onActivityCreated(savedInstanceState: Bundle?) {
            super.onActivityCreated(savedInstanceState)
            initiateUI()
        }


        fun checkValidation(): Boolean {
            if (TextUtils.isEmpty(etDateOfBirth.text.toString())) {
                showMessage(etDateOfBirth, getString(R.string.str_empty_dob))
                return false
            }
            return true
        }
    }

When I press next I get error: java.lang.IllegalStateException: etDateOfBirth must not be null Can anyone help out?

Didn't you define etDateOfBirth? Define edit text on onViewCreated()

EditText etDateOfBirth = view.findViewById(R.id.sample);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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