为什么我不能在Kotlin设置听众?

时间:2017-12-09 15:03:09

标签: android callback kotlin

我有OnClickInterface(方法有趣onClickShape())Main.class,FlipFragment.class和ImageView(在我的代码中调用图像)。我的目标是让形象倾听。

interface OnClickInterface {
  fun onClickShape()
}

MainActivity

class MainActivity : AppCompatActivity() {



  override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_main)
    initTabs()
    var flip = FlipFragment()
    flip.listener = object : OnClickInterface {
      override fun onClickShape() {
        Log.d("MainActivity", "Shape Pressed")
        ToastUtils.showSuccessMessage(baseContext, "sometext")
      }

    } 
  }

  fun initTabs() {
    var adapter = TabsPagerFragmentAdapter(supportFragmentManager)
    mViewPager.adapter = adapter
    mTabLayout.setupWithViewPager(mViewPager)
  }
}

on FliteFragment中的onCreate

var image = view.findViewById<ImageView>(R.id.fShapeView)
    image.setOnClickListener(View.OnClickListener {
      Log.d("FlipFragment", "PRESSED")
      if (listener != null)
        listener!!.onClickShape()
    })

App正在加载,没有错误。但是当我按下我在日志中显示的图像时FlipFragment:PRESSED,这意味着我的应用程序调用FragmentFlip方法,而不是来自MainActivity的覆盖方法。为什么呢?

我搜索了错误。我的应用程序在这里显示NPE。

 flip.listener = object : OnClickInterface {
              override fun onClickShape() {
                Log.d("MainActivity", "Shape Pressed")
                ToastUtils.showSuccessMessage(baseContext, "someText")
              }}

为什么listener = null。我用匿名类定义了它。

FlipFragment中的所有代码

class FlipFragment : Fragment() {
  private var layout = R.layout.view_flip
  var listener: OnClickInterface? = null

  override fun onCreateView(inflater: LayoutInflater?, container: ViewGroup?,
      savedInstanceState: Bundle?): View? {
    var view: View
    view = inflater!!.inflate(layout, container, false)
    var image = view.findViewById<ImageView>(R.id.fShapeView)
    image.setOnClickListener(View.OnClickListener {
      Log.d("FlipFragment", "PRESSED")
        if (listener != null){
         listener!!.onClickShape()}
    })
    return view
  }

  companion object {
    fun getInstanse(): FlipFragment {
      var args = Bundle()
      var flipFragment = FlipFragment()
      flipFragment.arguments = args
      return flipFragment
    }

  }


}

如果您需要所有代码,则为FragmentPagerAdapter.class

class TabsPagerFragmentAdapter(fm: FragmentManager?) : FragmentPagerAdapter(fm) {
  var tabs: Array<String> = arrayOf("Flip", "Multi")

  override fun getItem(position: Int) = when(position){
      0 -> FlipFragment.getInstanse()
      1 -> Mulit.getInstanse() //it is empty now
    else -> FlipFragment.getInstanse()
    }


  override fun getPageTitle(position: Int) = tabs[position]


  override fun getCount() = tabs.size
}

0 个答案:

没有答案