P
P
Pavel2020-12-19 12:07:13
Android
Pavel, 2020-12-19 12:07:13

How to use setOnClickListener in a tab fragment?

Made a small application consisting of two tabs. On one tab there are buttons on clicking on which certain actions should be performed. The application starts, the tabs work and all components are displayed on them.
The problem is that when assigning a function to buttonSpeed.setOnClickListener nothing happens.
I thought it was a fragment. Then I created a test application where only a fragment is present in activity_main.xml, in this fragment there is a button and the button worked for me there.
I thought maybe findViewById does not find the button, but the output in Logcat shows that the button is located.
Help me solve the problem, I'm new to android programming (I write in kotlin).
In the fragment file I do the following:

spoiler
override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        val rootView = inflater.inflate(R.layout.fragment_tab_item1, container, false)
        //здесь какой-то код...

        val buttonSpeed = rootView.findViewById<Button>(R.id.buttonSpeed)
        Log.i("---buttonSpeed.getTag()---", buttonSpeed.toString())
        buttonSpeed.setOnClickListener(::calcSpeed)

        return inflater.inflate(R.layout.fragment_tab_item1, container, false)
}
//здесь тоже разный код ...

fun calcSpeed (view: View){
            Toast.makeText(activity, "Введите расход воздуха в воздуховоде, м^3/ч", Toast.LENGTH_SHORT).show()
    }

Here is my activity_main.xml:
spoiler
<?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=".MainActivity">

    <androidx.viewpager.widget.ViewPager
        android:id="@+id/viewPager"
        android:layout_width="match_parent"
        android:layout_height="match_parent">

        <com.google.android.material.tabs.TabLayout
            android:id="@+id/tabLayout"
            android:layout_width="match_parent"
            android:layout_height="wrap_content">

            <com.google.android.material.tabs.TabItem
                android:id="@+id/tabItem1"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="@string/tabItem1Name" />

            <com.google.android.material.tabs.TabItem
                android:id="@+id/tabItem2"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="@string/tabItem2Name" />

        </com.google.android.material.tabs.TabLayout>
    </androidx.viewpager.widget.ViewPager>
</androidx.constraintlayout.widget.ConstraintLayout>

In MainActivity I only have tab creation:
spoiler
class MainActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        configureTabLayout() //функция настройки вкладок
    }

    //функция настройки вкладок
    private fun configureTabLayout() {
        val viewPager = findViewById<ViewPager>(R.id.viewPager)
        val tabLayout = findViewById<TabLayout>(R.id.tabLayout)

        TabPagerAdapter.Companion.setContext(this) //Передача контекста приложения в класс TabPagerAdapter

        val adapter = TabPagerAdapter (supportFragmentManager, tabLayout.tabCount)
        Log.i("---adapter.count---",adapter.count.toString())
        viewPager.adapter = adapter
        viewPager.addOnPageChangeListener( TabLayout.TabLayoutOnPageChangeListener (tabLayout))

        tabLayout.addOnTabSelectedListener( object: TabLayout.OnTabSelectedListener {
            override fun onTabSelected(tab: TabLayout.Tab) {
                viewPager.currentItem = tab.position
            }
            override fun onTabUnselected(tab: TabLayout.Tab?) { }
            override fun onTabReselected(tab: TabLayout.Tab?) { }
        })
    }
}

And this is the TabPagerAdapter class:
spoiler
class TabPagerAdapter (fm: FragmentManager, private var tabCount: Int) : FragmentPagerAdapter(fm) {
    override fun getItem(position: Int): Fragment {
        when (position) {
            0 -> return FragmentTabItem1()
            1 -> return FragmentTabItem2()
            else -> return FragmentTabItem2()
        }
    }

    //возвращает количество вкладок
    override fun getCount(): Int {
        return tabCount
    }

    //устанавливает название вкладок
    override fun getPageTitle(position: Int): CharSequence? {
        return when (position) {
            0 -> context.getString(R.string.tabItem1Name)
            1 -> context.getString(R.string.tabItem2Name)
            else -> {
                return context.getString(R.string.tabItem2Name)
            }
        }
    }

    companion object {
TabPagerAdapter.Companion.setContext(this)
        private lateinit var context: Context
        fun setContext(con: Context) {
            context = con
        }
    }
}

spoiler
5fddc3f00dde5264096592.jpeg

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
Denis Zagaevsky, 2020-12-19
@ellissar

You inflate one view, look for a button in it, then inflate a new view and return it. The first inflate is simply thrown away. Return its result, and everything will work.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question