为什么我无法在Android的TabLayout上更改或滑动选项卡?

时间:2019-05-07 02:31:12

标签: android kotlin android-tablayout

enter image description here

我想制作一个如上图的屏幕。因此,如果我在TabLayout中选择一个标签,则它将在向服务器发出请求之前更改一些变量,最终服务器中的数据将填充回收站视图。

我在TabLayout上使用addOnTabSelectedListener来检索更改(如果用户更改了选项卡)。通常在某些教程中,他们总是使用带有一些片段更改的选项卡布局,因此似乎他们使用viewPager来处理它。但是在这种情况下,我将其删除,而我仅使用addOnTabSelectedListener进行更改,并且因为我只需要一个回收者视图而不是多个片段

这是我在片段中使用的代码

class SearchResultFragment : Fragment() {

    lateinit var fragmentView : View
    lateinit var recyclerView : RecyclerView
    lateinit var tabLayout : TabLayout

    lateinit var mContext : Context
    lateinit var mActivity : FragmentActivity

    private var selectedEventType = EventType.kajianUmum
    private var selectedCity = City.defaultCityName
    private var selectedTime = "Akhir Pekan"

    lateinit var eventAdapter : GeneralEventRecyclerViewAdapter
    private var  eventList = ArrayList<Event>()

    override fun onAttach(context: Context) {
        super.onAttach(context)

        mContext = context
        activity?.let { mActivity = it }

    }

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        fragmentView = inflater.inflate(R.layout.fragment_search_result, container, false)

        setUpSafeArg()
        setUpViewsDeclaration()
        setUpListeners()

        initRecyclerView()


        return fragmentView
    }

    private fun setUpViewsDeclaration() {
        recyclerView = fragmentView.findViewById(R.id.recyclerView_event_general_search_result)
        tabLayout = fragmentView.findViewById(R.id.tabLayout_time_search_result)

    }

    private fun setUpSafeArg() {
        arguments?.let {

            val args = SearchResultFragmentArgs.fromBundle(it)
            selectedEventType = args.selectedEventType
            selectedCity = args.selectedCity
            selectedTime = args.selectedTime

        }
    }

    private fun setUpListeners() {

        tabLayout.addOnTabSelectedListener(object: TabLayout.OnTabSelectedListener {

            override fun onTabSelected(tab: TabLayout.Tab?) {

                when(tab?.position ?: 0) {
                    0 -> mActivity.toast("0")
                    1 ->  mActivity.toast("1")
                    2 ->  mActivity.toast("2")
                    3 ->  mActivity.toast("3")
                    4 ->  mActivity.toast("0")
                    else -> println("Number too high")
                }

            }

            override fun onTabReselected(tab: TabLayout.Tab?) {

            }

            override fun onTabUnselected(tab: TabLayout.Tab?) {

            }


        })

    }




    private fun initRecyclerView() {

        eventAdapter = GeneralEventRecyclerViewAdapter(mContext)
        val layoutManager = LinearLayoutManager(mContext, RecyclerView.VERTICAL,false)
        recyclerView.adapter = eventAdapter
        recyclerView.layoutManager = layoutManager

        eventAdapter.setOnItemClickListener(object: OnEventKMListener {

            override fun eventKMClicked(position: Int) {
                val selectedEvent = eventList[position]
                val eventDetailDestination = SearchResultFragmentDirections.actionGlobalDestinationEventDetail(selectedEvent)
                Navigation.findNavController(fragmentView).navigate(eventDetailDestination)
            }

        })

    }

}

但是我不知道为什么我在运行应用程序时无法更改选项卡,也无法滑动该选项卡。该选项卡停留在索引0

这是我的xml:

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.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:layout_width="match_parent"
                                                   android:layout_height="match_parent"
                                                   tools:context=".Fragments.Search.SearchResultFragment" android:id="@+id/constraintLayout_search_result">


    <com.google.android.material.tabs.TabLayout
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            app:layout_constraintStart_toStartOf="parent" android:layout_marginStart="16dp"
            app:layout_constraintEnd_toEndOf="parent" android:layout_marginEnd="16dp" android:layout_marginTop="16dp"
            app:layout_constraintTop_toTopOf="parent" android:id="@+id/tabLayout_time_search_result">

        <com.google.android.material.tabs.TabItem
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="Hari Ini"/>

        <com.google.android.material.tabs.TabItem
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="Besok"/>

        <com.google.android.material.tabs.TabItem
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="Akhir Pekan"/>

        <com.google.android.material.tabs.TabItem
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="Pekan Depan"/>

        <com.google.android.material.tabs.TabItem
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="Semua"/>

    </com.google.android.material.tabs.TabLayout>

    <androidx.recyclerview.widget.RecyclerView
            android:layout_width="379dp"
            android:layout_height="635dp"
            app:layout_constraintStart_toStartOf="parent" android:layout_marginStart="16dp"
            app:layout_constraintEnd_toEndOf="parent" android:layout_marginEnd="16dp"
            app:layout_constraintBottom_toBottomOf="parent" android:layout_marginTop="16dp"
            app:layout_constraintTop_toBottomOf="@+id/tabLayout_time_search_result"
            android:id="@+id/recyclerView_event_general_search_result"
            tools:listitem="@layout/item_general_event"/>

</androidx.constraintlayout.widget.ConstraintLayout>

这是我的MainActivity:

class MainActivity : AppCompatActivity(), NavController.OnDestinationChangedListener {

    private lateinit var navController : NavController
    lateinit var destinationTitleTextView : TextView
    lateinit var progressBar : ProgressBar
    lateinit var topToolbar : Toolbar
    lateinit var bottomNavigationView : BottomNavigationView


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

        FirebaseApp.initializeApp(this)

        // Initial Setup views
        navController = Navigation.findNavController(this,R.id.nav_host_fragment)
        setupBottomNavMenu(navController)
        setupActionBar(navController)
        setUpViewDeclaration()


        // Add Listeners
        navController.addOnDestinationChangedListener(this)


    }



    override fun dispatchTouchEvent(event: MotionEvent): Boolean {

        // to hide softkeyboard when tapping outside area in the fragment
        // And in the layout of the fragment use this attribute: android:focusableInTouchMode="true"

        if (event.action == MotionEvent.ACTION_DOWN) {
            val v = currentFocus
            if (v is EditText) {
                val outRect = Rect()
                v.getGlobalVisibleRect(outRect)
                if (!outRect.contains(event.rawX.toInt(), event.rawY.toInt())) {
                    v.clearFocus()
                    val imm = getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
                    imm.hideSoftInputFromWindow(v.windowToken, 0)
                }
            }
        }
        return super.dispatchTouchEvent(event)
    }



    private fun setUpViewDeclaration() {
        destinationTitleTextView = findViewById(R.id.destination_label_text_view)
        progressBar = findViewById(R.id.progressBar_main_activity)
        topToolbar = findViewById(R.id.top_toolbar)
        bottomNavigationView = findViewById(R.id.bottom_nav)

    }

    private fun setupBottomNavMenu(navController: NavController) {
        bottom_nav.setupWithNavController(navController)
    }


    private fun setupActionBar(navController: NavController) {

        setSupportActionBar(top_toolbar)
        supportActionBar?.setDisplayShowTitleEnabled(false)

        // set up top hierarchy destination
        val appBarConfiguration = AppBarConfiguration(setOf(
            R.id.destination_home,
            R.id.destination_search,
            R.id.destination_user_control,
            R.id.destination_create_event)
        )

        top_toolbar.setupWithNavController(navController,appBarConfiguration)

    }

    override fun onDestinationChanged(controller: NavController, destination: NavDestination, arguments: Bundle?) {

        progressBar.visibility = View.GONE // to ensure progress bar will be gone whenever the user segues to other destination




        // set toolbar and bottom navigation visibility
        if (destination.id == R.id.destination_welcome ||
            destination.id == R.id.destination_authentication ||
            destination.id == R.id.destination_loginUsingEmail ||
            destination.id == R.id.destination_registerUsingEmail ||
            destination.id == R.id.destination_choose_user_location ||
            destination.id == R.id.destination_change_password ||
            destination.id == R.id.destination_create_event_finished_info ||
            destination.id == R.id.destination_photo_view

        ) {

            topToolbar.visibility = View.GONE
            bottomNavigationView.visibility = View.GONE

        } else if (

            destination.id == R.id.destination_create_event_name ||
            destination.id == R.id.destination_create_event_type ||
            destination.id == R.id.destination_create_event_starting_date ||
            destination.id == R.id.destination_create_event_ending_date ||
            destination.id == R.id.destination_create_event_speaker ||
            destination.id == R.id.destination_create_event_description ||
            destination.id == R.id.destination_create_event_poster ||
            destination.id == R.id.destination_create_event_coordinate ||
            destination.id == R.id.destination_create_event_location_detail ||
            destination.id == R.id.destination_create_event_contact ||
            destination.id == R.id.destination_create_event_price ||
            destination.id == R.id.destination_create_event_capacity ||
            destination.id == R.id.destination_create_event_summary ||
            destination.id == R.id.destination_create_event_finished_info ||
            destination.id == R.id.destination_event_detail ||
            destination.id == R.id.destination_event_description_detail ||
            destination.id == R.id.destination_map_detail_location

        ) {

            topToolbar.visibility = View.VISIBLE
            bottomNavigationView.visibility = View.GONE

        } else if (
            destination.id == R.id.destination_user_control ||
            destination.id == R.id.destination_search

        ) {

            topToolbar.visibility = View.GONE
            bottomNavigationView.visibility = View.VISIBLE

        } else {

            topToolbar.visibility = View.VISIBLE
            bottomNavigationView.visibility = View.VISIBLE

        }







        // Set Toolbar Title
        if (destination.id == R.id.destination_home) {
            destinationTitleTextView.setText(R.string.home)
        } else if (destination.id == R.id.destination_create_event_summary) {
            destinationTitleTextView.text = "Ringkasan"
        } else if (
            destination.id == R.id.destination_create_event ||
            destination.id == R.id.destination_create_event_name ||
            destination.id == R.id.destination_create_event_type ||
            destination.id == R.id.destination_create_event_starting_date ||
            destination.id == R.id.destination_create_event_ending_date ||
            destination.id == R.id.destination_create_event_speaker ||
            destination.id == R.id.destination_create_event_description ||
            destination.id == R.id.destination_create_event_poster ||
            destination.id == R.id.destination_create_event_coordinate ||
            destination.id == R.id.destination_create_event_location_detail ||
            destination.id == R.id.destination_create_event_contact ||
            destination.id == R.id.destination_create_event_capacity ||
            destination.id == R.id.destination_create_event_price ||
            destination.id == R.id.destination_create_event_summary ||
            destination.id == R.id.destination_create_event_finished_info

        ) {

            destinationTitleTextView.setText(R.string.createEvent)

        } else {

            destinationTitleTextView.text = ""

        }




    }


}

这里出了什么问题? java没问题

1 个答案:

答案 0 :(得分:2)

您可以使用TabHost制作此东西,尽管这是一种旧方法。另一种方法是将viewpager包装在布局中。这是一些很好的教程。

  1. TabHost:https://www.dev2qa.com/android-tabhost-example/
  2. ViewPager:https://developer.android.com/guide/navigation/navigation-swipe-view