从活动中调用视图寻呼机片段中的函数

时间:2017-08-08 08:49:15

标签: android android-fragments android-activity kotlin

我的活动包含很少的复选框和一个每30秒滑动一次的视图寻呼机。当我选中父活动中的复选框时,我想更改图像。但是在调用函数" flipImage()"片段中的图像视图为null,当我单击图像时,onClickListener不起作用。

class SomeActivity : AppCompatActivity() {

    var viewPagerAdapter : SectionsPagerAdapter by Delegates.notNull<SectionsPagerAdapter>()
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        setContentView(R.layout.activity_image_slides)
        supportActionBar?.setDisplayHomeAsUpEnabled(true)

        viewPagerAdapter = SectionsPagerAdapter(supportFragmentManager)

        vp_image_slides.adapter = viewPagerAdapter

        btnImageFlip.setOnCheckedChangeListener({
            checkbox, b ->

            val slideImageFrag = viewPagerAdapter.getItem(vp_image_slides.currentItem) as SlideImageFragment
            slideImageFrag.flipImage()
        })
    }


    inner class SectionsPagerAdapter(fm: FragmentManager) : FragmentPagerAdapter(fm) {

        override fun getItem(position: Int): Fragment {


            return SlideImageFragment.newInstance(someUri)
        }

        override fun getCount(): Int {

            return 4
        }


    }

}

和我的片段

    class SlideImageFragment : Fragment() {

        var uri: Uri? = null
        val TAG = SlideImageFragment.javaClass.simpleName



        override fun onCreate(savedInstanceState: Bundle?) {
            super.onCreate(savedInstanceState)
            if (arguments != null) {
                uri = arguments.getParcelable(IMAGE_URI)

            }
        }


        override fun onViewCreated(view: View?, savedInstanceState: Bundle?) {
            super.onViewCreated(view, savedInstanceState)
            if (uri != null) {


                Glide.with(view).load(uri).into(iv_slide_image)

//Not working
                iv_slide_image.setOnClickListener {

                    val activity = activity as ImageSlidesActivity
                    activity.toggle()
                    Log.e(TAG, "Image is clicke2d")
                }

            }

        }



        fun flipImage() {


        //here I am getting iv_slide_image as null
            if (iv_slide_image != null)
                iv_slide_image.rotationX = 180f
        }


        override fun onCreateView(inflater: LayoutInflater?, container: ViewGroup?,
                                  savedInstanceState: Bundle?): View? {

            Log.e(TAG, "onCreateView")
            val view = inflater!!.inflate(R.layout.fragment_slide_image, container, false)


            return view

        }




        companion object {

            val IMAGE_URI = "image"
            fun newInstance(uri: Uri): SlideImageFragment {
                val fragment = SlideImageFragment()
                val args = Bundle()
                args.putParcelable(IMAGE_URI, uri)
                fragment.arguments = args
                return fragment
            }
        }
    }

0 个答案:

没有答案