【发布时间】:2022-01-05 22:17:29
【问题描述】:
我尝试在基本导航抽屉活动模板中基于现有的项目创建另一个项目。我像其他人一样设置它,但在我创建的项目/片段上出现此错误。
找不到符号 new ViewModelProvider(this).get(ProbaViewModel.class);
我希望它是可见的。这很有趣,因为在已经存在的片段上,默认情况下红色的线已经是红色的,但应用程序运行得很好。我只做的那个有问题。可能是什么问题呢?我使用的是 4.3 版本,因为这是我的课程所必需的。
public class ProbaFragment extends Fragment {
public ProbaViewModel probaViewModel;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
probaViewModel =
new ViewModelProvider(this).get(ProbaViewModel.class); // here
View root = inflater.inflate(R.layout.fragment_proba, container, false);
final TextView textView = root.findViewById(R.id.text_slideshow);
probaViewModel.getText().observe(getViewLifecycleOwner(), new Observer<String>() {
@Override
public void onChanged(@Nullable String s) {
textView.setText(s);
}
});
return root;
}
}
依赖关系
android {
compileSdkVersion 31
buildToolsVersion "30.0.3"
defaultConfig {
applicationId "com.example.proba2"
minSdkVersion 16
targetSdkVersion 31
versionCode 1
versionName "1.0"
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
}
}
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}
}
dependencies {
implementation 'androidx.appcompat:appcompat:1.4.0'
implementation 'com.google.android.material:material:1.4.0'
implementation 'androidx.constraintlayout:constraintlayout:2.1.2'
implementation 'androidx.navigation:navigation-fragment:2.3.5'
implementation 'androidx.navigation:navigation-ui:2.3.5'
implementation 'androidx.lifecycle:lifecycle-livedata-ktx:2.4.0'
implementation 'androidx.lifecycle:lifecycle-viewmodel-ktx:2.4.0'
implementation 'androidx.legacy:legacy-support-v4:1.0.0'
testImplementation 'junit:junit:4.+'
androidTestImplementation 'androidx.test.ext:junit:1.1.3'
androidTestImplementation 'androidx.test.espresso:espresso-core:3.4.0'
}
【问题讨论】:
-
看起来您需要导入。似乎 ViewModelProvider 无法识别
标签: java android android-studio class android-layout