超强大的Databinding 双向绑定简单demo

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();
            }
        });

    }
}

布局:





    
        
    

    

        

        

实际开发中使用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;
        }
    }
}

你可能感兴趣的:(超强大的Databinding 双向绑定简单demo)