万喜1990 2014-10-21 09:54 采纳率: 0%
浏览 1091

Handler里面不能更新界面 包括List和Button的显示 求大神解答

首先设置的是Activity的OnCrate方法

 public class CreateActivity extends Activity{
    protected static CharSequence text = "Waiting Range";
public static MobilocMaster mobilocMaster  = new MobilocMaster(); 
    public static MobilocAnchor mobilocAnchor  = new MobilocAnchor();       
    public static LoopThread lt;
    Button mButton;
    static boolean started = false;
    Handler handler;



protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    requestWindowFeature(Window.FEATURE_NO_TITLE);
    getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
            WindowManager.LayoutParams.FLAG_FULLSCREEN);
    setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);

    setContentView(R.layout.create);  
    ini(!started);      
    mButton = (Button) findViewById(R.id.button);
    mButton.setText(text);
    mButton.setOnClickListener(new OnClickListener() {
        public void onClick(View arg0) {
            Intent intent1 = new Intent(CreateActivity.this,CoordinateActivity.class);
            startActivity(intent1);
           }
        }); 

然后是处理函数和初始化

public void handleMessage(Message msg) {
               switch (msg.what) {
               case 1:  
                   text = "Waiting Range";
                   mButton.setEnabled(false);
                   mButton.setText(text);
                   data.clear();
                   Hashtable<String,myAnchorInfo> temp = (Hashtable<String,myAnchorInfo>)msg.obj;
                   Enumeration t = temp.keys();
                   while(t.hasMoreElements()) {
                        String t1 = (String)t.nextElement();
                        myAnchorInfo myi = (myAnchorInfo)temp.get(t1);
                        map = new HashMap<String, String>();
                        map.clear();
                        map.put("name", myi.name);
                        map.put("ip", myi.ip);
                        map.put("range", myi.range);
                        data.add(map);
                   }
                   adapter.notifyDataSetChanged();
                   System.out.println(data.toString()+"Data的数据[test]");
                   System.out.println("Handler更新界面--->Waiting Range[test]");
                   break;                  
               case 2:                  
                   text = "Look Position";
                   mButton.setEnabled(true);
                   mButton.setText(text);
                   data.clear();
                   Hashtable<String,myAnchorInfo> temp1 = (Hashtable<String,myAnchorInfo>)msg.obj;
                   System.out.println(msg.obj.toString()+"Message的信息[test]");
                   Enumeration t2 = temp1.keys();
                   while(t2.hasMoreElements()) {
                        String t3 = (String)t2.nextElement();
                        myAnchorInfo myi = (myAnchorInfo)temp1.get(t3);
                        map = new HashMap<String, String>();
                        map.clear();
                        map.put("name", myi.name);
                        map.put("ip", myi.ip);
                        map.put("range", myi.range);
                        data.add(map);
                   }
                   adapter.notifyDataSetChanged(); 
                   System.out.println(data.toString()+"Data的数据[test]");
                   System.out.println("Handler更新界面--->Look Position[test]");
                   break;
               }                  
           }
       };           
}   
void ini(Boolean flag){
    if(flag)
    {
        Intent intent = getIntent();
        String myname = intent.getStringExtra("myName");
        rangingSettings();
        mobilocAnchor.setAnchorName(myname);
        mobilocMaster.start();
        mobilocAnchor.start();

        ListView lv = (ListView) findViewById(R.id.list1);  
        String[] from = new String[]{"name" , "ip", "range"};
        int[] to = new int[]{R.id.person_name , R.id.person_ip , R.id.person_range};
        adapter = new SimpleAdapter(this, data,R.layout.child_create, from,to);  
        lv.setAdapter(adapter);  
        started = true;

       lt = new LoopThread();
       lt.start();
    }
}

最后是子线程来更新数据

class LoopThread extends Thread{
    Boolean flag = true;
    public void run() {
            while(true) {
                try {
                    Thread.sleep(3000);
                    tempAnchor.clear();
                } catch (InterruptedException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
                while(true){
                    try {
                        Thread.sleep(300);
                    } catch (InterruptedException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                    if(mobilocAnchor.getMyAddress()!= null){
                        myAnchor = new AnchorInfo(mobilocAnchor.getMyAddress()); 
                        break;
                    }                       
                }
                Enumeration akey = MobilocMaster.anchorTable.keys();
                Enumeration rkey = MobilocMaster.rangingTable.keys();
                while(akey.hasMoreElements()) {
                    AnchorNetInfo key1 = (AnchorNetInfo)akey.nextElement();
                    AnchorInfo ai = (AnchorInfo)MobilocMaster.anchorTable.get(key1);
                    if(myAnchor.getHostString().contains(ai.getHostString()))
                        continue;
                    tempInfo.setAnchorInfo(ai.getName(), ai.getIP());
                    myAnchorPair = new AnchorPair(myAnchor.getHostString(),ai.getHostString());
                    if(LocationAnchor.readyForRanging){                         
                        tempInfo.setRange(MobilocAnchor.rangingTable.get(myAnchorPair).getDistance());
                        tempAnchor.put(ai.getName(),tempInfo);
                        flag = false;
                    }
                    else{
                        tempInfo.setRange("Ranging");
                        tempAnchor.put(ai.getName(),tempInfo);
                    }                   
                }
                if(flag){
                    Message message = new Message();
                    message.what = 1;
                    message.obj = tempAnchor;
                    System.out.println(message.obj.toString()+"主线程Message信息[test]");
                    handler.sendMessage(message);
                }   
                else
                {
                    Message message1 = new Message();
                    message1.what = 2;
                    message1.obj = tempAnchor;
                    handler.sendMessage(message1);
                    System.out.println(message1.obj.toString()+"主线程Message1信息[test]");
                    flag = true;
                } 
            }

    }       
   } 

class myAnchorInfo{
    String name;
    String range;
    String ip;

    public void setAnchorInfo(String name,String ip){
        this.name = name;
        this.ip = ip;
    }

    public void setRange(float ft){
        this.range = (float)(Math.round(ft*100))/100+"";
    }

    public void setRange(String range){
        this.range = range;
    }
}
  • 写回答

1条回答

  • ChatGPTᴼᴾᴱᴺᴬᴵ 2023-05-27 00:16
    关注

    该回答引用ChatGPT-3.5,仅供参考,不保证完全正确

    根据你提供的代码,我看到你在处理函数中使用了一个Handler来更新界面,但是你遇到了无法更新界面的问题。在Android中,只有主线程(也称为UI线程)才能更新UI界面,而你的Handler是在子线程中执行的,因此不能直接更新UI。


    解决这个问题的一种常见方法是使用runOnUiThread()方法或者Handlerpost()方法来在主线程中更新UI界面。下面是修改后的代码示例:


    首先,在handleMessage()方法中,你可以使用runOnUiThread()方法来更新UI界面:

    public void handleMessage(Message msg) {
        switch (msg.what) {
            case 1:  
                // 更新UI界面的操作
                runOnUiThread(new Runnable() {
                    public void run() {
                        text = "Waiting Range";
                        mButton.setEnabled(false);
                        mButton.setText(text);
                        data.clear();
                        // ... 更新ListView的数据
                        adapter.notifyDataSetChanged();
                    }
                });
                break;
            case 2:
                // 更新UI界面的操作
                runOnUiThread(new Runnable() {
                    public void run() {
                        text = "Look Position";
                        mButton.setEnabled(true);
                        mButton.setText(text);
                        data.clear();
                        // ... 更新ListView的数据
                        adapter.notifyDataSetChanged();
                    }
                });
                break;
        }
    }
    

    另一种方法是使用Handlerpost()方法来在主线程中更新UI界面:

    public void handleMessage(Message msg) {
        switch (msg.what) {
            case 1:  
                // 更新UI界面的操作
                handler.post(new Runnable() {
                    public void run() {
                        text = "Waiting Range";
                        mButton.setEnabled(false);
                        mButton.setText(text);
                        data.clear();
                        // ... 更新ListView的数据
                        adapter.notifyDataSetChanged();
                    }
                });
                break;
            case 2:
                // 更新UI界面的操作
                handler.post(new Runnable() {
                    public void run() {
                        text = "Look Position";
                        mButton.setEnabled(true);
                        mButton.setText(text);
                        data.clear();
                        // ... 更新ListView的数据
                        adapter.notifyDataSetChanged();
                    }
                });
                break;
        }
    }
    

    这样修改后,你的UI更新操作应该能在主线程中执行,从而更新UI界面。请根据你的需求选择其中一种方法进行修改。

    评论

报告相同问题?

悬赏问题

  • ¥15 电力市场出清matlab yalmip kkt 双层优化问题
  • ¥30 ros小车路径规划实现不了,如何解决?(操作系统-ubuntu)
  • ¥20 matlab yalmip kkt 双层优化问题
  • ¥15 如何在3D高斯飞溅的渲染的场景中获得一个可控的旋转物体
  • ¥88 实在没有想法,需要个思路
  • ¥15 MATLAB报错输入参数太多
  • ¥15 python中合并修改日期相同的CSV文件并按照修改日期的名字命名文件
  • ¥15 有赏,i卡绘世画不出
  • ¥15 如何用stata画出文献中常见的安慰剂检验图
  • ¥15 c语言链表结构体数据插入