问题
(Note: this is a follow up question to Is it possible to use androidx-navigation with onClick-databinding without writing boilercode in Fragment?
I want to use androidx-databinding to handle onClick calling a static method with parameters
Utils.myNavigate(...) via the xml-layout-file
My Code below is verifyed by the compile process but is never called when i click on the button.
How to fix this?
My Layoutfile:
<layout ...>
<data>
<import type="de.k3b.androidx.navigationdemo.R" />
<import type="de.k3b.androidx.navigationdemo.Utils" />
</data>
<RelativeLayout ...>
<Button ...
android:onClick="@{view -> Utils.myNavigate(view,
R.id.action_gallery_to_editProperties)}"
/>
</RelativeLayout>
</layout>
My Static Method implementation:
public class Utils {
public static final String TAG = "Utils";
public static void myNavigate(View view, @IdRes int id) {
// this gets never called neither with `Object view` nor with `View view`
Log.d (TAG, "myNavigate clicked");
// Navigation.findNavController(view).navigate(id);
}
}
global project build.gradle
buildscript {
repositories {
google()
jcenter()
}
dependencies {
classpath 'com.android.tools.build:gradle:3.4.0'
classpath "android.arch.navigation:navigation-safe-args-gradle-plugin:1.0.0"
}
}
allprojects {
repositories {
google()
jcenter()
}
}
app build.gradle
apply plugin: 'com.android.application'
android {
compileSdkVersion 28
defaultConfig {
applicationId "de.k3b.androidx.navigationdemo"
minSdkVersion 15
targetSdkVersion 28
versionCode 1
versionName "1.0"
}
buildTypes {
debug {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
}
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
}
}
dataBinding.enabled=true
}
dependencies {
implementation 'androidx.appcompat:appcompat:1.0.0'
implementation 'androidx.legacy:legacy-support-v4:1.0.0'
implementation 'android.arch.navigation:navigation-fragment:1.0.0'
implementation 'android.arch.navigation:navigation-ui:1.0.0'
}
回答1:
You might have forgot to bind the layout with the activity.
Change
setContentView(R.layout.your_layout_file);
To
DataBindingUtil.setContentView(this, R.layout.your_layout_file);
If that's not the issue, you may check the working sample I created on calling static method using data binding.
来源:https://stackoverflow.com/questions/56074061/howto-androidx-databinding-for-onclick-to-static-method-with-parameter