如何使用kotlin添加按钮Fragments,ViewPager

时间:2018-07-31 20:23:40

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

我想添加一个按钮(id ='Home'),它将带我进入使用这些代码的主要活动,但没有反应,这是我在GITHUB中的项目的示例,请从{{3}中进行检查}(问题已通过@ advice-dog修复,已添加到该项目中)

在我的ViewPager布局中:

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/bg2"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:theme="@style/AppFullScreenTheme"
    tools:context=".License">


    <android.support.v4.view.ViewPager
        android:id="@+id/view_pager"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:visibility="visible"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

</android.support.constraint.ConstraintLayout>

我在那里上课:

package com.medanis.fneclis


import android.content.Intent
import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import android.support.v4.view.ViewPager
import kotlinx.android.synthetic.main.activity_license.*


class License : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_license)
        val viewPager = findViewById<ViewPager>(R.id.view_pager)
        viewPager.adapter = CustomPagerAdapter(this)

    }
}

在ViewPager的第一个PAGE中,其中有主页按钮:

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/l1_bg"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@drawable/fneclis_l1_bg"
    tools:context=".AllButtons">


    <Button
        android:id="@+id/Home"
        android:layout_width="56dp"
        android:layout_height="53dp"
        android:layout_marginBottom="523dp"
        android:layout_marginEnd="312dp"
        android:layout_marginLeft="16dp"
        android:layout_marginRight="312dp"
        android:layout_marginStart="16dp"
        android:layout_marginTop="16dp"
        android:background="@drawable/ic_home_black_24dp"
        android:contentDescription="@string/todo"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />
</android.support.constraint.ConstraintLayout>

与类AllButtons有关(我想在ViewPage的大多数页面中使用它,但不是全部):

package com.medanis.fneclis

import android.content.Intent 
import android.os.Bundle 
import android.support.v7.app.AppCompatActivity 
import kotlinx.android.synthetic.main.activity_l1_page.*

class AllButtons: AppCompatActivity() {

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

// those are some other pages which contains the same button and they are inside the ViewPager
           /* setContentView(R.layout.activity_l2_page)
            setContentView(R.layout.activity_l3_page)
            setContentView(R.layout.activity_m1page)
            setContentView(R.layout.activity_m2page)*/

        Home.setOnClickListener{
            val intent = Intent(this, MainActivity::class.java)
            startActivity(intent)
        }
    } }

适配器:

package com.medanis.fneclis

import android.app.Activity
import android.content.Context
import android.support.v4.view.PagerAdapter
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup

class CustomPagerAdapter(private val mContext: Context) : PagerAdapter() {

    override fun instantiateItem(collection: ViewGroup, position: Int): Any {
        val modelObject = ModelObject.values()[position]
        val inflater = LayoutInflater.from(mContext)
        val viewGroup = inflater.inflate(modelObject.titleResId, collection, false) as ViewGroup
        collection.addView(viewGroup)
        return viewGroup
    }

    override fun destroyItem(collection: ViewGroup, position: Int, view: Any) {
        collection.removeView(view as View)
    }

    override fun getCount(): Int {
        return ModelObject.values().size
    }

    override fun isViewFromObject(view: View, `object`: Any): Boolean {

        return view === `object`
    }

    override fun getPageTitle(position: Int): CharSequence {
        val customPagerEnum = ModelObject.values()[position]
        return mContext.getString(customPagerEnum.titleResId)
    }

    override fun getItemPosition(`object`: Any): Int {
        return super.getItemPosition(`object`)
    }
}

ModelObject:

package com.medanis.fneclis

enum class ModelObject private constructor(val titleResId: Int ) {

    LICENSEONE(R.layout.activity_l1_page),
    PAGEONE(R.layout.activity_l1s1page),
    PAGETWO(R.layout.activity_l1s2page),

    LICENSETWO(R.layout.activity_l2_page),
    PAGETHREE(R.layout.activity_l2_s3page),
    PAGEFOUR(R.layout.activity_l2_s4page),

    LICENSETHREE(R.layout.activity_l3_page),
    PAGEFIVE(R.layout.activity_l3_s5page),
    PAGESIX(R.layout.activity_l3_s6page),

}

2 个答案:

答案 0 :(得分:0)

首先,您没有在视图分页器中使用AllButtons活动,而只是在CustomPagerAdapter上使用布局并将其填充,并且由于您没有使用该活动,未设置主页按钮上的点击监听器。

  • 一些重要的知识。通过android view pager documentation。正如您在该页面上看到的那样,您只能将片段添加到视图分页器中。因此,您需要将AllButtons转换为Fragment。然后在onViewCreated的{​​{1}}方法上设置点击监听器。

       
    Fragment

然后在您的视图寻呼机适配器上创建该片段的一个实例(通过在class AllButtonsFragment: Fragment() { override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? { val root = inflater.inflate(R.layout.activity_l1_page, container, false) return root } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) home.setOnClickListener { val intent = Intent(this, MainActivity::class.java) startActivity(intent) } } } 上创建一个称为Fragment的静态函数来实现这一点,以达到良好的作法)并在{ {1}}功能取决于位置。

newInstance()

答案 1 :(得分:0)

我重新编写了一些代码,我将解释一些有关如何改进的提示和建议。

首先,始终将ActvitiyFragment添加到ActivitiesFragments的末尾,这将使事情更容易理解。

class LicenseActivity : AppCompatActivity() {

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

        // You can simply use the id of the View here.
        view_pager.adapter = CustomPagerAdapter(supportFragmentManager)
    }
}

接下来,我将您的AllButtons Activity更改为Fragment

此代码稍微复杂一点,但是它使用的是非常常见的模式newInstance模式。要创建新的Fragment,您需要创建一个静态方法,该方法将返回一个Fragment,并将您的值传递到arguments中。

因此,要多解释一下。您创建了一个名为newInstance的函数,该函数获取Fragment应该知道的信息,在这种情况下,我们希望它显示的布局。

接下来,您创建一个Bundle,并将布局放入其中。

最后,您将Fragment的参数分配给Bundle

这是创建Fragments的最安全方法。

class AllButtonsFragment : Fragment() {

    companion object {
        private const val EXTRA_COLOR = "EXTRA_COLOR"
        private const val EXTRA_LAYOUT = "EXTRA_LAYOUT"

        fun newInstance(modelObject: ModelObject): Fragment {
            val fragment = AllButtonsFragment()

            // Creating a Bundle with the various values we want to pass, such as the color and layout.
            val bundle = Bundle()
            bundle.putInt(EXTRA_COLOR, modelObject.titleResId)
            bundle.putInt(EXTRA_LAYOUT, modelObject.layoutResId)
            fragment.arguments = bundle

            return fragment
        }
    }

    // Getting the layout from the arguments to inflate the View.
    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
        val layout = arguments?.getInt(EXTRA_LAYOUT)
                ?: throw IllegalStateException("arguments does not contain a layout.")
        return inflater.inflate(layout, container, false)
    }

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

        val color = arguments?.getInt(EXTRA_COLOR)
        // TODO: Do whatever with your colour.

        // Using findViewById since this isn't on every layout.
        view?.findViewById<View>(R.id.Home)?.setOnClickListener {
            val intent = Intent(context, MainActivity::class.java)
            startActivity(intent)
        }
    }
}

接下来,我重写了您的AdapterFragments一起使用。这只会获取页面的位置,将其传递给我们的newInstance函数,并为您获取Fragment

class CustomPagerAdapter(fm: FragmentManager) : FragmentStatePagerAdapter(fm) {

    override fun getItem(position: Int): Fragment {
        val modelObject = ModelObject.values()[position]
        // Creating a new instance of our Fragment with this Model Object.
        return AllButtonsFragment.newInstance(modelObject)
    }

    override fun getCount() = ModelObject.values().size
}