【发布时间】:2019-08-22 07:13:42
【问题描述】:
我正在开发一个需要TabLayout 绑定到ViewPager2 的android 应用程序。阅读this 并按照here 中的代码,我需要使用TabLayoutMediator。但是在导入它时,我面临Unresolved reference 错误。我知道这个错误指的是什么,但我在依赖项和导致错误的东西中找不到任何问题。如第二个链接所述,此类包含在androidx.viewpager2:viewpager2:1.0.0-beta03 中,这是该链接所讨论内容的更新版本。我还尝试将版本降级到链接中提到的版本,但效果不佳。这是我的build.gradle 文件:
apply plugin: 'com.android.application'
apply plugin: 'kotlin-android'
apply plugin: 'kotlin-android-extensions'
android {
compileSdkVersion 29
buildToolsVersion "29.0.2"
defaultConfig {
applicationId "com.example.myapp"
minSdkVersion 19
targetSdkVersion 29
versionCode 1
versionName "1.0"
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
}
}
}
dependencies {
implementation fileTree(dir: 'libs', include: ['*.jar'])
implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version"
implementation 'androidx.appcompat:appcompat:1.0.2'
implementation 'androidx.core:core-ktx:1.0.2'
implementation 'androidx.constraintlayout:constraintlayout:1.1.3'
implementation 'androidx.legacy:legacy-support-v4:1.0.0'
testImplementation 'junit:junit:4.12'
androidTestImplementation 'androidx.test:runner:1.2.0'
androidTestImplementation 'androidx.test.espresso:espresso-core:3.2.0'
implementation 'androidx.legacy:legacy-support-core-utils:1.0.0'
implementation 'com.google.android.material:material:1.0.0'
implementation 'androidx.viewpager2:viewpager2:1.0.0-beta03'
}
这是我的MainActivity 文件:
package com.example.myapp
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import androidx.viewpager2.widget.ViewPager2
import com.google.android.material.tabs.TabLayout
import com.google.android.material.tabs.TabLayoutMediator
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
val viewpager : ViewPager2 = findViewById(R.id.view_pager)
val demoAdapter = DemoViewPagerAdapter(this)
viewpager.adapter = demoAdapter
val tabs : TabLayout = findViewById(R.id.tab_layout)
TabLayoutMediator(tabs, viewpager) { tab, position ->
tab.text = demoAdapter.getPageTitle(position)
}
}
}
对我应该做什么有什么想法吗?
【问题讨论】:
-
你做过
clean/rebuild project吗?如果它不起作用,只需使缓存无效并重新启动它应该可以工作。 -
此外,由于您使用的是
Kotlin,因此您可以导入此import kotlinx.android.synthetic.main.activity_main.*,这样您就可以避免findViewById()的事情 -
@Skizo-ozᴉʞS 是的,我已经尝试清理和重建项目。没有任何改变。
-
你能把你的依赖改成这些吗:
implementation "com.google.android.material:material:1.1.0-alpha07"implementation "androidx.viewpager2:viewpager2:1.0.0-alpha05" -
因为您没有使用较新的依赖项。你的 gradle 有
'com.google.android.material:material:1.0.0'(注意版本1.0.0)。TablayoutMediator被添加到1.1.0我猜
标签: android kotlin android-tablayout android-viewpager2