2.事件绑定

2016-10-10  本文已影响0人  C二叔

事件处理类

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

}
上一篇 下一篇

猜你喜欢

热点阅读