如何在Kotlin中使用按钮单击切换viewpager选项卡?

时间:2019-05-20 14:23:45

标签: android android-fragments kotlin android-viewpager android-tablayout

我想通过单击片段本身内部的按钮来切换片段。我已经创建了viewpager + tablayout,在我创建了一个与活动进行通信的界面之前,一切都可以正常工作,在其中我可以为Viewpager设置不同的Page。我对Kotlin还是很陌生,我不明白为什么我要赶上NullPointer :( 我可能还没有很好地初始化我的按钮,但是我不确定

这是我的MainActivity代码

class MainActivity : AppCompatActivity()
, MyFragment1.buttonClick {

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_main)

    tablayout.addTab(tablayout.newTab().setIcon(R.drawable.ic_fragment1))
    tablayout.addTab(tablayout.newTab().setIcon(R.drawable.ic_fragment_2))
    tablayout.addTab(tablayout.newTab().setIcon(R.drawable.ic_fragment3))
    tablayout.tabGravity = TabLayout.GRAVITY_FILL

    val adapter = MyAdapter(this, supportFragmentManager, tablayout.tabCount)
    viewpager!!.adapter = adapter

    viewpager.addOnPageChangeListener(TabLayout.TabLayoutOnPageChangeListener(tablayout))


    val tabStrip = tablayout.getChildAt(0) as LinearLayout
    for (i in 0 until tabStrip.childCount) {
        tabStrip.getChildAt(i).setOnTouchListener { v, event -> true }
    }
}


override fun buttonClicked(view: View) {
    viewpager.currentItem = 2
}

fun selectIndex(index: Int) {
    viewpager.currentItem = index
}

override fun onBackPressed() {
    val currentPos = viewpager.currentItem
    if (currentPos != 0) {
        viewpager.currentItem = 0
    } else {
        super.onBackPressed()
    }
}
}



**And a code for my Fragment**



 class MyFragment1 : Fragment() {

private  var click: buttonClick? = null

interface buttonClick {
    fun buttonClicked(view: View)
}

var currentPage: Int = 0


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

    val view: View = inflater.inflate(R.layout.fragment_my_fragment1, container, false)
    val btn: Button = view?.findViewById(R.id.btn_next)

    btn.setOnClickListener {
        Toast.makeText(context, "test", Toast.LENGTH_LONG).show()
        click?.buttonClicked(it)

    }

    return view
}

}

1 个答案:

答案 0 :(得分:0)

您是否初始化了click变量?

private var click: buttonClick? = null

override fun onAttach(context: Context?) {
    super.onAttach(context)
    click = context as? buttonClick
}

override fun onDetach() {
    super.onDetach()
    click = null
}