【问题标题】:how can i add button Fragments,ViewPager using kotlin如何使用 kotlin 添加按钮片段、ViewPager
【发布时间】:2018-07-31 20:23:40
【问题描述】:

我想添加一个按钮(id='Home'),它带我进入我使用这些代码但它没有反应的主要活动,这是我在 GITHUB 中的项目示例,请从 HERE 检查它(问题已被@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 的第一页中,我有 Home 按钮:

<?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`)
    }
}

模型对象:

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),

}

【问题讨论】:

  • 你如何使用你的AllButtons类?您似乎只是在您的 Adapter 中构建了一个 View,而不是使用 AllButtons 类。
  • 我是初学者,请告诉我该怎么做?
  • 给我几分钟。
  • 慢慢来,请不要忘记我^_^
  • 这些答案对您有帮助吗?

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


【解决方案1】:

我稍微重写了你的代码,我会解释一些关于如何改进的提示和建议。

首先,始终将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)
        }
    }
}

接下来,我重写了您的 Adapter 以使用 Fragments。这只会获取页面的位置,将其传递给我们的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
}

【讨论】:

  • 它在 AllButtonFragment 上给我一个错误:return setContentView(layout)
  • 和 Intent()
  • 我在github上添加了一个项目示例,请查看
  • 好吧,我犯了一些错误。我修复了它们,我什至为你的 repo 提出了更改请求。现在应该一切正常。我已经更新了答案以反映这些代码更改。
  • 谢谢,我明天检查一下,告诉你发生了什么^_^再次感谢
【解决方案2】:

首先,您没有在视图寻呼机中使用 AllButtons 活动,您只是在使用布局并将其膨胀到 CustomPagerAdapter 上,并且由于您没有使用活动,因此点击监听器打开主页按钮未设置。

  • 有几件重要的事情要知道。通过安卓view pager documentation。正如您在该页面上看到的那样,您只能将片段添加到视图寻呼机。所以您需要将您的AllButtons 转换为Fragment。然后在FragmentonViewCreated方法上设置点击监听。

    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 上创建一个名为newInstance() 的静态函数来实现此目的)并在instantiateItem 函数上返回适当的片段,具体取决于位置上。

    override fun instantiateItem(collection: ViewGroup, position: Int): Any {

         return when (position) {
             0 -> A_FUNCTION.newInstance()
             1 -> B_FUNCTION.newInstance()
             else -> C_FUNCTION.newInstance()
         }
    }

【讨论】:

  • 它给了我关于 A_function / b_Function 和 C_Function 的错误
  • 我在github上添加了一个项目示例,请查看
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-09-17
  • 1970-01-01
  • 1970-01-01
  • 2015-11-11
  • 2020-04-18
  • 1970-01-01
相关资源
最近更新 更多