先上代码:
配置文件:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent">
<ImageView
android:id="@+id/welcome"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@drawable/welcome"
android:contentDescription="logo"/>
</LinearLayout>
代码一:
public class MainActivity extends Activity {
private ImageView image;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
image = (ImageView)findViewById(R.id.welcome);
image.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
new Thread(new Runnable() {
@Override
public void run() {
// TODO Auto-generated method stub
Message message = Message.obtain();
message.what = 1;
handler.sendMessage(message);
}
}).start();
}
});
}
Handler handler = new Handler(){
@Override
public void handleMessage(Message msg) {
// TODO Auto-generated method stub
if(msg.what==1){
image.setImageResource(R.drawable.welcome_uu);
}else{
image.setImageResource(R.drawable.welcome);
}
}
};
}
代码二:
public class MainActivity extends Activity {
private ImageView image;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
image = (ImageView)findViewById(R.id.welcome);
image.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
Message message = Message.obtain();
message.what = 1;
handler.sendMessage(message);
}
});
}
Handler handler = new Handler(){
@Override
public void handleMessage(Message msg) {
// TODO Auto-generated method stub
if(msg.what==1){
image.setImageResource(R.drawable.welcome_uu);
}else{
image.setImageResource(R.drawable.welcome);
}
}
};
}
代码二中没有用到
new Thread(new Runnable() {...等代码,但是依然可以执行得到效果;那么这段代码可以省略吗,如果两个有不同,不同在什么地方,在那种情形之下会用到其差异?多谢大神们指教!谢谢。
------解决方案--------------------
在你的程序中如果只是点击后发一个message 去设置一下背景的话,可以直接在 @Override
public void onClick(View v) {
// TODO Auto-generated method stub
image.setImageResource(R.drawable.welcome_uu);
}
,开线程主要做耗时的事情,如网络操作!
------解决方案--------------------
handler 是用于从线程中操作界面上的东西的, 楼主这种单击的情况完全用不着这么绕道.
而代码一显然是绕了两道, 代码二是绕了一道, 都是不必要的.