当前位置: 代码迷 >> Android >> fragment 内部异步更新UI,该如何解决
  详细解决方案

fragment 内部异步更新UI,该如何解决

热度:594   发布时间:2016-04-28 02:09:16.0
fragment 内部异步更新UI
我想在fragment中用不断地更换topmargin来做一个可挤压的抽屉,但在Fragment中用runable结合hander报ui线程错误
public class fragment_mylight extends Fragment {
 private Handler handler=null;  
private LinearLayout drawer;
private final int MARGIN_HEIGHT_ONCE=20;
private int marginHeight;
private int drawerHeight;
private boolean flag;
@Override
 public View onCreateView(LayoutInflater inflater, ViewGroup container,  
            Bundle savedInstanceState) {
  handler=new Handler();  
View view =inflater.inflate(com.ks.uidemo.R.layout.fragment_mylight, container,false);
 drawer=(LinearLayout)view.findViewById(R.id.dropdown_drawer);
RelativeLayout content =(RelativeLayout)view.findViewById(R.id.drawer_content);
final ImageButton handerButton=(ImageButton)view.findViewById(R.id.drawer_hander);
ViewTreeObserver vob =handerButton.getViewTreeObserver();
 LinearLayout.LayoutParams lp =new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT,drawerHeight);
// lp.topMargin=-150;
// drawer.setLayoutParams(lp);
  final Handler mHandler = new Handler(){ 
 @Override  
public void handleMessage(Message msg) {
 LinearLayout.LayoutParams ll=(LinearLayout.LayoutParams)msg.obj;
 drawer.setLayoutParams(ll);
 super.handleMessage(msg);
 }

};
vob.addOnPreDrawListener(new OnPreDrawListener(){

@Override
public boolean onPreDraw() {
 drawerHeight=drawer.getLayoutParams().height;
int width=handerButton.getMeasuredHeight();
 marginHeight=drawerHeight-width;
 LinearLayout.LayoutParams lp =new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT,drawerHeight);
lp.topMargin=-marginHeight;
//drawer.setLayoutParams(lp);
return true;
}

});
final Runnable runable=new Runnable(){
@Override
public void run() {
int timer;
if(marginHeight%MARGIN_HEIGHT_ONCE==0)timer=marginHeight/MARGIN_HEIGHT_ONCE;
else timer=marginHeight/MARGIN_HEIGHT_ONCE+1;
int margin=flag?MARGIN_HEIGHT_ONCE:-MARGIN_HEIGHT_ONCE;
for(int i=0;i<timer;i++){
LinearLayout.LayoutParams lp1 =new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT,drawerHeight);
if(margin>0){
lp1.topMargin=Math.max(lp1.bottomMargin+margin,0);
}
else{
lp1.topMargin=Math.min(lp1.bottomMargin+margin,-marginHeight);
}

try {
Thread.sleep(20);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
mHandler.obtainMessage(1, lp1).sendToTarget();
}
}

};
handerButton.setOnClickListener(new OnClickListener(){
@Override
public void onClick(View arg0) {
flag=flag==true?false:true;
    new Thread(runable).start();//在这里报 only the original thread that created a view hierarchy can touch its view
}

});
    return view; 
}

------解决思路----------------------
对topmargin的处理,直接放handler里吧,发消息出去就行了
------解决思路----------------------
直接在handler里面操作呀!
  相关解决方案