私はこのオブジェクトを持っています
ObservableInt someNumber;
public ObservableInt getSomeNumber()
{
return someNumber;
}
public void setSomeNumber(ObservableInt number)
{
this.someNumber = number;
}
そして、私のAppCompatEditTextはxmlコードで次のようになります:
<Android.support.v7.widget.AppCompatEditText
Android:layout_width="0dp"
Android:layout_height="@dimen/agro_item_height"
Android:layout_weight="1"
Android:inputType="numberDecimal"
Android:text="@={String.valueOf(myObject.someNumber)}"
Android:gravity="center_horizontal"/>
私はこのエラーが発生しています:
Error:Execution failed for task ':app:compileDebugJavaWithJavac'.
Java.lang.RuntimeException: failure, see logs for details.
cannot generate view binders Java.lang.NullPointerException
at Android.databinding.tool.expr.MethodCallExpr.generateCode(MethodCallExpr.Java:69)
at Android.databinding.tool.expr.Expr.toFullCode(Expr.Java:745)
at Android.databinding.tool.expr.Expr.assertIsInvertible(Expr.Java:767)
at Android.databinding.tool.BindingTarget.addInverseBinding(BindingTarget.Java:68)
at Android.databinding.tool.LayoutBinder.<init>(LayoutBinder.Java:228)
at Android.databinding.tool.DataBinder.<init>(DataBinder.Java:52)
at Android.databinding.tool.CompilerChef.ensureDataBinder(CompilerChef.Java:83)
at Android.databinding.tool.CompilerChef.sealModels(CompilerChef.Java:168)
at Android.databinding.annotationprocessor.ProcessExpressions.writeResourceBundle(ProcessExpressions.Java:149)
at Android.databinding.annotationprocessor.ProcessExpressions.onHandleStep(ProcessExpressions.Java:82)
at Android.databinding.annotationprocessor.ProcessDataBinding$ProcessingStep.runStep(ProcessDataBinding.Java:154)
at Android.databinding.annotationprocessor.ProcessDataBinding$ProcessingStep.access$000(ProcessDataBinding.Java:139)
at Android.databinding.annotationprocessor.ProcessDataBinding.process(ProcessDataBinding.Java:66)
at com.Sun.tools.javac.processing.JavacProcessingEnvironment.callProcessor(JavacProcessingEnvironment.Java:794)
at com.Sun.tools.javac.processing.JavacProcessingEnvironment.discoverAndRunProcs(JavacProcessingEnvironment.Java:705)
at com.Sun.tools.javac.processing.JavacProcessingEnvironment.access$1800(JavacProcessingEnvironment.Java:91)
at com.Sun.tools.javac.processing.JavacProcessingEnvironment$Round.run(JavacProcessingEnvironment.Java:1035)
at com.Sun.tools.javac.processing.JavacProcessingEnvironment.doProcessing(JavacProcessingEnvironment.Java:1176)
at com.Sun.tools.javac.main.JavaCompiler.processAnnotations(JavaCompiler.Java:1170)
at com.Sun.tools.javac.main.JavaCompiler.compile(JavaCompiler.Java:856)
at com.Sun.tools.javac.main.Main.compile(Main.Java:523)
at com.Sun.tools.javac.api.JavacTaskImpl.doCall(JavacTaskImpl.Java:129)
at com.Sun.tools.javac.api.JavacTaskImpl.call(JavacTaskImpl.Java:138)
at org.gradle.api.internal.tasks.compile.JdkJavaCompiler.execute(JdkJavaCompiler.Java:46)
at org.gradle.api.internal.tasks.compile.JdkJavaCompiler.execute(JdkJavaCompiler.Java:33)
at org.gradle.api.internal.tasks.compile.NormalizingJavaCompiler.delegateAndHandleErrors(NormalizingJavaCompiler.Java:104)
at org.gradle.api.internal.tasks.compile.NormalizingJavaCompiler.execute(NormalizingJavaCompiler.Java:53)
at org.gradle.api.internal.tasks.compile.NormalizingJavaCompiler.execute(NormalizingJavaCompiler.Java:38)
at org.gradle.api.internal.tasks.compile.CleaningJavaCompilerSupport.execute(CleaningJavaCompilerSupport.Java:35)
at org.gradle.api.internal.tasks.compile.CleaningJavaCompilerSupport.execute(CleaningJavaCompilerSupport.Java:25)
at org.gradle.api.tasks.compile.JavaCompile.performCompilation(JavaCompile.Java:163)
at org.gradle.api.tasks.compile.JavaCompile.compile(JavaCompile.Java:145)
at org.gradle.api.tasks.compile.JavaCompile.compile(JavaCompile.Java:93)
at com.Android.build.gradle.tasks.factory.AndroidJavaCompile.compile(AndroidJavaCompile.Java:49)
at Sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at Sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.Java:62)
at Sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.Java:43)
at Java.lang.reflect.Method.invoke(Method.Java:498)
at org.gradle.internal.reflect.JavaMethod.invoke(JavaMethod.Java:75)
at org.gradle.api.internal.project.taskfactory.AnnotationProcessingTaskFactory$IncrementalTaskAction.doExecute(AnnotationProcessingTaskFactory.Java:245)
at org.gradle.api.internal.project.taskfactory.AnnotationProcessingTaskFactory$StandardTaskAction.execute(AnnotationProcessingTaskFactory.Java:221)
at org.gradle.api.internal.project.taskfactory.AnnotationProcessingTaskFactory$IncrementalTaskAction.execute(AnnotationProcessingTaskFactory.Java:232)
at org.gradle.api.internal.project.taskfactory.AnnotationProcessingTaskFactory$StandardTaskAction.execute(AnnotationProcessingTaskFactory.Java:210)
at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter.executeAction(ExecuteActionsTaskExecuter.Java:80)
at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter.executeActions(ExecuteActionsTaskExecuter.Java:61)
at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter.execute(ExecuteActionsTaskExecuter.Java:46)
at org.gradle.api.internal.tasks.execution.PostExecutionAnalysisTaskExecuter.execute(PostExecutionAnalysisTaskExecuter.Java:35)
at org.gradle.api.internal.tasks.execution.SkipUpToDateTaskExecuter.execute(SkipUpToDateTaskExecuter.Java:66)
at org.gradle.api.internal.tasks.execution.ValidatingTaskExecuter.execute(ValidatingTaskExecuter.Java:58)
at org.gradle.api.internal.tasks.execution.SkipEmptySourceFilesTaskExecuter.execute(SkipEmptySourceFilesTaskExecuter.Java:52)
at org.gradle.api.internal.tasks.execution.SkipTaskWithNoActionsExecuter.execute(SkipTaskWithNoActionsExecuter.Java:52)
at org.gradle.api.internal.tasks.execution.SkipOnlyIfTaskExecuter.execute(SkipOnlyIfTaskExecuter.Java:53)
at org.gradle.api.internal.tasks.execution.ExecuteAtMostOnceTaskExecuter.execute(ExecuteAtMostOnceTaskExecuter.Java:43)
at org.gradle.execution.taskgraph.DefaultTaskGraphExecuter$EventFiringTaskWorker.execute(DefaultTaskGraphExecuter.Java:203)
at org.gradle.execution.taskgraph.DefaultTaskGraphExecuter$EventFiringTaskWorker.execute(DefaultTaskGraphExecuter.Java:185)
at org.gradle.execution.taskgraph.AbstractTaskPlanExecutor$TaskExecutorWorker.processTask(AbstractTaskPlanExecutor.Java:66)
at org.gradle.execution.taskgraph.AbstractTaskPlanExecutor$TaskExecutorWorker.run(AbstractTaskPlanExecutor.Java:50)
at org.gradle.execution.taskgraph.DefaultTaskPlanExecutor.process(DefaultTaskPlanExecutor.Java:25)
at org.gradle.execution.taskgraph.DefaultTaskGraphExecuter.execute(DefaultTaskGraphExecuter.Java:110)
at org.gradle.execution.SelectedTaskExecutionAction.execute(SelectedTaskExecutionAction.Java:37)
at org.gradle.execution.DefaultBuildExecuter.execute(DefaultBuildExecuter.Java:37)
at org.gradle.execution.DefaultBuildExecuter.access$000(DefaultBuildExecuter.Java:23)
at org.gradle.execution.DefaultBuildExecuter$1.proceed(DefaultBuildExecuter.Java:43)
at org.gradle.execution.DryRunBuildExecutionAction.execute(DryRunBuildExecutionAction.Java:32)
at org.gradle.execution.DefaultBuildExecuter.execute(DefaultBuildExecuter.Java:37)
at org.gradle.execution.DefaultBuildExecuter.execute(DefaultBuildExecuter.Java:30)
at org.gradle.initialization.DefaultGradleLauncher$4.run(DefaultGradleLauncher.Java:153)
at org.gradle.internal.Factories$1.create(Factories.Java:22)
at org.gradle.internal.progress.DefaultBuildOperationExecutor.run(DefaultBuildOperationExecutor.Java:91)
at org.gradle.internal.progress.DefaultBuildOperationExecutor.run(DefaultBuildOperationExecutor.Java:53)
at org.gradle.initialization.DefaultGradleLauncher.doBuildStages(DefaultGradleLauncher.Java:150)
at org.gradle.initialization.DefaultGradleLauncher.access$200(DefaultGradleLauncher.Java:32)
at org.gradle.initialization.DefaultGradleLauncher$1.create(DefaultGradleLauncher.Java:98)
at org.gradle.initialization.DefaultGradleLauncher$1.create(DefaultGradleLauncher.Java:92)
at org.gradle.internal.progress.DefaultBuildOperationExecutor.run(DefaultBuildOperationExecutor.Java:91)
at org.gradle.internal.progress.DefaultBuildOperationExecutor.run(DefaultBuildOperationExecutor.Java:63)
at org.gradle.initialization.DefaultGradleLauncher.doBuild(DefaultGradleLauncher.Java:92)
at org.gradle.initialization.DefaultGradleLauncher.run(DefaultGradleLauncher.Java:83)
at org.gradle.launcher.exec.InProcessBuildActionExecuter$DefaultBuildController.run(InProcessBuildActionExecuter.Java:99)
at org.gradle.tooling.internal.provider.runner.BuildModelActionRunner.run(BuildModelActionRunner.Java:46)
at org.gradle.launcher.exec.ChainingBuildActionRunner.run(ChainingBuildActionRunner.Java:35)
at org.gradle.tooling.internal.provider.runner.SubscribableBuildActionRunner.run(SubscribableBuildActionRunner.Java:58)
at org.gradle.launcher.exec.ChainingBuildActionRunner.run(ChainingBuildActionRunner.Java:35)
at org.gradle.launcher.exec.InProcessBuildActionExecuter.execute(InProcessBuildActionExecuter.Java:48)
at org.gradle.launcher.exec.InProcessBuildActionExecuter.execute(InProcessBuildActionExecuter.Java:30)
at org.gradle.launcher.exec.ContinuousBuildActionExecuter.execute(ContinuousBuildActionExecuter.Java:81)
at org.gradle.launcher.exec.ContinuousBuildActionExecuter.execute(ContinuousBuildActionExecuter.Java:46)
at org.gradle.launcher.daemon.server.exec.ExecuteBuild.doBuild(ExecuteBuild.Java:52)
at org.gradle.launcher.daemon.server.exec.BuildCommandOnly.execute(BuildCommandOnly.Java:36)
at org.gradle.launcher.daemon.server.api.DaemonCommandExecution.proceed(DaemonCommandExecution.Java:120)
at org.gradle.launcher.daemon.server.exec.WatchForDisconnection.execute(WatchForDisconnection.Java:37)
at org.gradle.launcher.daemon.server.api.DaemonCommandExecution.proceed(DaemonCommandExecution.Java:120)
at org.gradle.launcher.daemon.server.exec.ResetDeprecationLogger.execute(ResetDeprecationLogger.Java:26)
at org.gradle.launcher.daemon.server.api.DaemonCommandExecution.proceed(DaemonCommandExecution.Java:120)
at org.gradle.launcher.daemon.server.exec.RequestStopIfSingleUsedDaemon.execute(RequestStopIfSingleUsedDaemon.Java:34)
at org.gradle.launcher.daemon.server.api.DaemonCommandExecution.proceed(DaemonCommandExecution.Java:120)
at org.gradle.launcher.daemon.server.exec.ForwardClientInput$2.call(ForwardClientInput.Java:74)
at org.gradle.launcher.daemon.server.exec.ForwardClientInput$2.call(ForwardClientInput.Java:72)
at org.gradle.util.Swapper.swap(Swapper.Java:38)
at org.gradle.launcher.daemon.server.exec.ForwardClientInput.execute(ForwardClientInput.Java:72)
at org.gradle.launcher.daemon.server.api.DaemonCommandExecution.proceed(DaemonCommandExecution.Java:120)
at org.gradle.launcher.daemon.server.health.DaemonHealthTracker.execute(DaemonHealthTracker.Java:47)
at org.gradle.launcher.daemon.server.api.DaemonCommandExecution.proceed(DaemonCommandExecution.Java:120)
at org.gradle.launcher.daemon.server.exec.LogToClient.doBuild(LogToClient.Java:60)
at org.gradle.launcher.daemon.server.exec.BuildCommandOnly.execute(BuildCommandOnly.Java:36)
at org.gradle.launcher.daemon.server.api.DaemonCommandExecution.proceed(DaemonCommandExecution.Java:120)
at org.gradle.launcher.daemon.server.exec.EstablishBuildEnvironment.doBuild(EstablishBuildEnvironment.Java:72)
at org.gradle.launcher.daemon.server.exec.BuildCommandOnly.execute(BuildCommandOnly.Java:36)
at org.gradle.launcher.daemon.server.api.DaemonCommandExecution.proceed(DaemonCommandExecution.Java:120)
at org.gradle.launcher.daemon.server.health.HintGCAfterBuild.execute(HintGCAfterBuild.Java:41)
at org.gradle.launcher.daemon.server.api.DaemonCommandExecution.proceed(DaemonCommandExecution.Java:120)
at org.gradle.launcher.daemon.server.exec.StartBuildOrRespondWithBusy$1.run(StartBuildOrRespondWithBusy.Java:50)
at org.gradle.launcher.daemon.server.DaemonStateCoordinator$1.run(DaemonStateCoordinator.Java:237)
at org.gradle.internal.concurrent.ExecutorPolicy$CatchAndRecordFailures.onExecute(ExecutorPolicy.Java:54)
at org.gradle.internal.concurrent.StoppableExecutorImpl$1.run(StoppableExecutorImpl.Java:40)
at Java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.Java:1142)
at Java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.Java:617)
at Java.lang.Thread.run(Thread.Java:745)
私はすでに試しました
Android:text="@={myObject.someNumber}"
しかし、私はこのエラーが発生しています:
Error:Execution failed for task ':app:compileDebugJavaWithJavac'.
Java.lang.RuntimeException: Found data binding errors.
****/ data binding error ****msg:Cannot find the getter for attribute 'Android:text' with value type int on Android.support.v7.widget.AppCompatEditText.
file:C:\Users\Moviit\AndroidStudioProjects\pbbchile-Android\app\src\main\res\layout\row_agro_tab.xml
loc:51:8 - 60:48
****\ data binding error ****
誰もこれを行う方法の例がありますか?
@LongRangerのバインディングアダプターのおかげで、ソリューションをさらに向上させることができましたが、アダプターとコードを変更する必要がありました。まず、次のようにObservableIntメンバーを初期化する必要がありました。
ObservableInt someNumber;
public ObservableInt getSomeNumber()
{
return someNumber;
}
public void setSomeNumber(ObservableInt number)
{
this.someNumber = number;
}
第二に、@ LongRangerが提供するアダプターを次のように変更する必要がありました。
@BindingAdapter("Android:text")
public static void bindIntegerInText(AppCompatEditText tv, int value)
{
tv.setText(String.valueOf(value));
// Set the cursor to the end of the text
tv.setSelection(tv.getText().length());
}
@InverseBindingAdapter(attribute = "Android:text")
public static int getIntegerFromBinding(TextView view)
{
String string = view.getText().toString();
return string.isEmpty() ? 0 : Integer.parseInt(string);
}
そうすれば、エラーを回避できます:@InverseBindingAdapterでInteger.parse(...)を実行しようとすると、無効なint ""になります。この後、@ BindingAdapterを使用して、EditTextの最後にカーソルを置く必要がありました。それ以外の場合、カーソルは先頭に移動し続けました。
単純なプリミティブ変換のための未公開のトリックがあります。
<Android.support.v7.widget.AppCompatEditText
Android:layout_width="0dp"
Android:layout_height="@dimen/agro_item_height"
Android:layout_weight="1"
Android:inputType="numberDecimal"
Android:text="@={`` + myObject.someNumber}"
Android:gravity="center_horizontal"/>
Android Studio 2.2。
EditTextで双方向バインディングを実行できます。
一方向のデータバインディングを使用して、属性に値を設定し、その属性の変更に反応するリスナーを設定できます
<Android.support.v7.widget.AppCompatEditText
...
Android:text="@={model.someString}"
/>
<Android.support.v7.widget.AppCompatEditText
...
Android:text="@={`` + model.someNumber}"
/>
``2つのアポストロフィが自動的にバインドします
documentation からわかるように、双方向バインディングは多くの目的に使用できます。
Android:checked="@={model.checked}"
Android:checkedButton
Android:checkedButton="@={model.selectedId}"
Android:rating
Android:rating="@={model.rating}"
等.
@CommonsWareは正しいので、ObservableInt
の代わりに_ObservableField<String>
_を使用する必要があります。本当に数値として必要な場合は、Integer.valueOf(stringNumber)
を解析するだけです。
_public ObservableField<String> someNumber;
//and in xml code:
<EditText
Android:layout_width="0dp"
Android:layout_height="@dimen/agro_item_height"
Android:layout_weight="1"
Android:inputType="numberDecimal"
Android:text="@={myObject.someNumber}"
Android:gravity="center_horizontal"/>
_
[〜#〜] edited [〜#〜]:または、前述のように、カスタム@InverseBindingAdapterを記述します
_public class MyEditTextBindingAdapters {
@BindingConversion
public static String intToStr(Integer value) {
return value != null ? String.valueOf(value) : "";
}
@InverseBindingAdapter(attribute = "Android:text")
public static Integer captureIntValue(EditText view) {
long value = 0;
try {
value = Integer.parseInt(view.getText().toString());
} catch (NumberFormatException e) {
e.printStackTrace();
}
return value;
}
}
_
前述の@George Mountとしてカスタムセッターを使用しようとしました( https://medium.com/google-developers/Android-data-binding-custom-setters-55a25a7aea47#.vsry4d95w )この答えによって( 整数型のAndroid双方向バインディングによりデータバインディングが存在しない )
双方向バインディングには元のコードを引き続き使用できます。
モデルクラス
public class Age {
private ObservableInt someNumber;
private ObservableField<String> someStr;
public Age() {
someNumber = new ObservableInt();
someStr = new ObservableField<>();
}
public ObservableInt getSomeNumber() {
return someNumber;
}
public void setSomeNumber(ObservableInt pSomeNumber) {
someNumber.set(pSomeNumber.get());
}
public ObservableField<String> getSomeStr() {
return someStr;
}
public void setSomeStr(ObservableField<String> pSomeStr) {
someStr.set(pSomeStr.get());
}
}
属性のカスタムセッターとゲッター
@BindingAdapter("Android:text")
public static void bindIntegerInText(AppCompatEditText tv, int value) {
tv.setText(String.valueOf(value));
}
@InverseBindingAdapter(attribute = "Android:text")
public static int getIntegerFromBinding(TextView view) {
return Integer.parseInt(view.getText().toString());
}
アクティビティのコード
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
ActivityMain2Binding binding = DataBindingUtil.setContentView(this, R.layout.activity_main2);
mAge = new Age();
mAge.setSomeNumber(new ObservableInt(3));
mAge.setSomeStr(new ObservableField<>("Test"));
binding.setAge(mAge);
binding.btn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
mAge.setSomeNumber(new ObservableInt(4));
mAge.setSomeStr(new ObservableField<>("Hello World"));
}
});
}
ObservableInt、Observable、通常のStringリソース、およびXML内のバインディングStringリソースを使用して4つのデモを作成します。
<string name="helloworld">Hello World</string>
activity_main3.xml
<?xml version="1.0" encoding="utf-8"?>
<layout xmlns:Android="http://schemas.Android.com/apk/res/Android"
>
<data>
<variable
name="age"
type="example.com.testerapplication.Age"/>
</data>
<LinearLayout
Android:layout_width="match_parent"
Android:layout_height="match_parent"
Android:orientation="vertical">
<Android.support.v7.widget.AppCompatEditText
Android:layout_width="match_parent"
Android:layout_height="wrap_content"
Android:text="@={age.someNumber}"/>
<Android.support.v7.widget.AppCompatEditText
Android:layout_width="match_parent"
Android:layout_height="wrap_content"
Android:text="@={age.someStr}"/>
<Android.support.v7.widget.AppCompatEditText
Android:layout_width="match_parent"
Android:layout_height="wrap_content"
Android:text="@string/helloworld"/>
<Android.support.v7.widget.AppCompatEditText
Android:layout_width="match_parent"
Android:layout_height="wrap_content"
Android:text="@{@string/helloworld}"/>
<Button
Android:id="@+id/btn"
Android:layout_width="match_parent"
Android:layout_height="wrap_content"
Android:text="Test"
/>
</LinearLayout>
</layout>
これを行うだけです:
Android:text="@={user.username}"
完全なコード:
<EditText
Android:id="@+id/username"
Android:layout_width="match_parent"
Android:layout_height="wrap_content"
Android:hint="user name"
Android:text="@={user.username}"/>
ユーザークラス
public class User {
public ObservableField<String> username = new ObservableField<>();
public ObservableField<String> password = new ObservableField<>();
public User() {
this("", "");
}
public User(String username, String password) {
this.username.set(username);
this.password.set(password);
}