美文网首页
2.事件绑定

2.事件绑定

作者: C二叔 | 来源:发表于2016-10-10 13:14 被阅读0次

    事件处理类

    public class EventHandlers {    
    
    public void handleClick ( View view){
            Toast.makeText(view.getContext(),"clicked",Toast.LENGTH_SHORT).show();    
        }  
      
    }
    

    xml文件中

    <?xml version="1.0" encoding="utf-8"?>
    <layout xmlns:android="http://schemas.android.com/apk/res/android">
    
    <data>    
      <variable        
      type="com.lefeee.dbdemoapplication.bean.User"        
      name="user" />    
    
    /*事件的类型和名称*/
      <variable        
      type="com.lefeee.dbdemoapplication.EventHandlers"
      name="handlers"  />
    </data>
    
    <LinearLayout    xmlns:tools="http://schemas.android.com/tools"    
    android:id="@+id/activity_main"    
    android:layout_width="match_parent"    
    android:layout_height="match_parent"    
    android:orientation="vertical"    
    tools:context="com.lefeee.dbdemoapplication.MainActivity">   
    
     <TextView        
    android:layout_width="wrap_content"        
    android:layout_height="wrap_content"        
    android:text="@{user.username}" />   
     
    <TextView        
    android:layout_width="match_parent"        
    android:layout_height="wrap_content" 
    android:text="@{user.password}"        
    android:clickable="true"        
    android:onClick="@{ handlers.handleClick}"  />   // 添加绑定事件
    
    </LinearLayout>
    
    </layout>
    

    activity中

    public class MainActivity extends AppCompatActivity {    
    @Override    
    protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
           
    ActivityMainBinding binding = DataBindingUtil.setContentView(this, R.layout.activity_main);        
    User user1 = new User("yuanlin", "123456");        
    binding.setUser( user1 );   
    
    /*添加绑定事件*/     
    EventHandlers mHandler = new EventHandlers();      
    binding.setHandlers(mHandler);    
    }
    
    }
    

    相关文章

      网友评论

          本文标题:2.事件绑定

          本文链接:https://www.haomeiwen.com/subject/bpamyttx.html