package com.example.myapplication;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;
import androidx.databinding.DataBindingUtil;
import com.example.myapplication.databinding.ActivityMainBinding;
public class MainActivity extends AppCompatActivity {
ActivityMainBinding binding;
Button button;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
binding = DataBindingUtil.setContentView(this, R.layout.activity_main);
button=findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Toast.makeText(MainActivity.this,String.valueOf(StringUtils.num),Toast.LENGTH_SHORT).show();
}
});
}
}
布局:
<?xml version="1.0" encoding="utf-8"?>
<layout 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">
<data>
<import type="com.example.myapplication.StringUtils"/>
</data>
<androidx.constraintlayout.widget.ConstraintLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<EditText
android:id="@+id/three"
android:layout_width="100dp"
android:layout_height="40dp"
android:layout_marginTop="100dp"
android:text="@={StringUtils.getString(StringUtils.num)}"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<Button
android:id="@+id/button"
android:layout_width="100dp"
android:layout_height="40dp"
android:layout_marginTop="100dp"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@id/three" />
</androidx.constraintlayout.widget.ConstraintLayout>
</layout>
实际开发中使用viewmodel,这里用Stringutils,简单替代:一样的原理。
package com.example.myapplication;
import androidx.databinding.InverseMethod;
public class StringUtils {
public static int num;
@InverseMethod("getCode")
public static String getString(int code) {
if (code == 1) {
return "第一";
} else if (code == 2) {
return "第二";
} else {
return "未知";
}
}
public static int getCode(String name){
if (name.equals("第一")){
return 1;
}else if (name.equals("第二")){
return 2;
}else {
return 0;
}
}
}