在安卓系统中如何刷新视图或活动界面?

4
我有一个活动从服务器(数据库)接收JSON对象,并且每个名为视图(TableLayout但在ScrollView中)的活动自动更新。但是当我从当前活动或直接从数据库中删除数据时,布局不会更新。
我尝试使用removeView方法,调用setContentView“再次”并重新初始化布局,最后我使用了startActivityfinish方法。但我认为如果像每10秒钟使用setInterval方法(但在Android上),那将很奇怪。
有人知道如何在用户没有注意到视图已被刷新的情况下刷新视图或活动吗?
感谢您的回复,如果我错了,请原谅。请让我知道我的错误。我在Google上搜索了整整一天,但没有找到解决方案。
我正在测试Android 2.2和Linux操作系统仿真器,这是我的代码:
package com.player;

import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.entity.BufferedHttpEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONException;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.SAXParseException;

import com.maestro.Mylist.SideMenuClick;
import com.maestro.libs.Functions;
import com.maestro.libs.SQLiteDatabaseConnector;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.DialogInterface.OnCancelListener;
import android.database.Cursor;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.view.ViewGroup.LayoutParams;
import android.widget.ImageButton;
import android.widget.ScrollView;
import android.widget.TableLayout;
import android.widget.TableRow;
import android.widget.TextView;
import android.widget.Toast;

public class Playlist extends Activity {
private int page = 0;
private TableLayout tblContainer;
private int totalPage;

private String selectedItemIndex;
private TableRow selectedItem;
private Drawable rowColor;

// info to request page
private String roomName;
private String serverAddress;
private String playerUsername;
private String layoutUsername;

private Bundle stateTmp;

/**
 * 
 */
public Playlist() {
    // TODO Auto-generated constructor stub
}


public void getSong(){
    this.tblContainer = new TableLayout(this);

    StringBuilder builder = new StringBuilder();
    HttpClient httpClient = new DefaultHttpClient();
    HttpGet httpGet = new HttpGet(this.serverAddress + "/index.php?m=playlist&a=list&room=" + this.roomName + 
            "&p=" + page + "&ax=ok");
    Functions.showAlert(this, this.serverAddress + "/index.php?m=playlist&a=list&room=" + this.roomName + 
            "&p=" + page + "&ax=ok");

    try{
        HttpResponse response = httpClient.execute(httpGet);
        // httpClient.notify();
        HttpEntity ht = response.getEntity();
        InputStream content = ht.getContent();
        BufferedReader reader = new BufferedReader(new InputStreamReader(content));
        String line;

        while ((line = reader.readLine()) != null) {
            builder.append(line);
        }

        try {
            JSONArray obj = new JSONArray(builder.toString());

            for(int i=1, j=0; i<obj.length(); i++, j++){
                TableRow tr = new TableRow(this);
                tr.setOnClickListener(new View.OnClickListener() {

                    @Override
                    public void onClick(View arg0) {
                        // TODO Auto-generated method stub
                        // Functions.showAlert(getRef(), arg0.getTag().toString());
                        selectedItem = (TableRow) arg0;
                        rowColor = arg0.getBackground();
                        arg0.setBackgroundColor(0xFFFFA500);

                        selectedItemIndex = arg0.getTag().toString();
                        showDialog(0);
                    }
                });

                if((j % 2) == 0){
                    tr.setBackgroundColor(0xff00ffff);
                }
                tr.setTag(obj.getJSONObject(i).getString("id"));

                TextView td = new TextView(this);
                td.setText(obj.getJSONObject(i).getString("songtitle"));
                td.setTextSize(30);
                td.setTextColor(0xff000000);
                tr.addView(td, 350, 40);

                TextView td2 = new TextView(this);
                td2.setText(obj.getJSONObject(i).getString("artist"));
                td2.setTextSize(30);
                td2.setTextColor(0xff000000);
                tr.addView(td2, 350, 40);

                this.tblContainer.addView(tr);
            }

        } catch (JSONException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

    }catch(ClientProtocolException cpe){
        Functions.showAlert(this, cpe.toString());

    }catch(IOException e){
        Functions.showAlert(this, e.toString());

    }

}


/**
 * 
 */
public void onCreate(Bundle savedInstanceState) {
    // TODO Auto-generated constructor stub
    super.onCreate(savedInstanceState);
    this.stateTmp = savedInstanceState;

    getWindow().addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
    requestWindowFeature(Window.FEATURE_NO_TITLE);
    setTitle("Maestro - Playlist");
    setContentView(R.layout.playlist);

    // get room name(location)
    if(savedInstanceState == null){
        Bundle tmp = this.getIntent().getExtras();
        if(tmp != null){
            this.roomName = tmp.getString("room_name");
            this.serverAddress = tmp.getString("server_address");
            this.playerUsername = tmp.getString("player_username");
            this.layoutUsername = tmp.getString("layout_username");
        }
    }

    /*SideMenuClick changeMenu = new SideMenuClick();
    ImageButton sideMenuSonglist = (ImageButton) findViewById(R.id.songlist);
    sideMenuSonglist.setOnClickListener(changeMenu);

    ImageButton sideMenuKeyControl = (ImageButton) findViewById(R.id.keycontrol);
    sideMenuKeyControl.setOnClickListener(changeMenu);

    ImageButton sideMenuMylist = (ImageButton) findViewById(R.id.mylist);
    sideMenuMylist.setOnClickListener(changeMenu);

    getSong();
    ScrollView sc = (ScrollView) findViewById(R.id.listcontainer);
    sc.addView(this.tblContainer);

    TextView txt = (TextView) findViewById(R.id.pagedesc);
    txt.setText((this.page+1) + " / " + this.totalPage);
    txt.setTextColor(0xff000000);

    ImageButton next = (ImageButton) findViewById(R.id.next);
    next.setOnClickListener(changeMenu);

    ImageButton prev = (ImageButton) findViewById(R.id.prev);
    prev.setOnClickListener(changeMenu);*/

    drawLayout(true);
}

public void drawLayout(boolean isFirst){
    if(isFirst == true){
        // getWindow().addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
        // requestWindowFeature(Window.FEATURE_NO_TITLE);
        // setTitle("Maestro - Playlist");
    }


    SideMenuClick changeMenu = new SideMenuClick();
    ImageButton sideMenuSonglist = (ImageButton) findViewById(R.id.songlist);
    sideMenuSonglist.setOnClickListener(changeMenu);

    ImageButton sideMenuKeyControl = (ImageButton) findViewById(R.id.keycontrol);
    sideMenuKeyControl.setOnClickListener(changeMenu);

    ImageButton sideMenuMylist = (ImageButton) findViewById(R.id.mylist);
    sideMenuMylist.setOnClickListener(changeMenu);

    getSong();
    ScrollView sc = (ScrollView) findViewById(R.id.listcontainer);
    sc.addView(this.tblContainer);

    TextView txt = (TextView) findViewById(R.id.pagedesc);
    txt.setText((this.page+1) + " / " + this.totalPage);
    txt.setTextColor(0xff000000);

    ImageButton next = (ImageButton) findViewById(R.id.next);
    next.setOnClickListener(changeMenu);

    ImageButton prev = (ImageButton) findViewById(R.id.prev);
    prev.setOnClickListener(changeMenu);
}

public Context getRef(){
    return this;
}

public void changeActivity(int layoutId){
    Intent newActivity = new Intent();
    newActivity.putExtra("room_name", this.roomName);
    newActivity.putExtra("server_address", this.serverAddress);
    newActivity.putExtra("player_username", this.playerUsername);
    newActivity.putExtra("layoyt_username", this.layoutUsername);

    if(R.id.songlist == layoutId){
        newActivity.setClass(this, ListSongs.class);
        startActivity(newActivity);

    }else if(R.id.keycontrol == layoutId){
        newActivity.setClass(this, KeyControl.class);
        startActivity(newActivity);

    }else if(R.id.mylist == layoutId){
        newActivity.setClass(this, Mylist.class);
        startActivity(newActivity);

    }else if(R.id.prev == layoutId){
        if(page > 0){
            page--;
        }

        ScrollView sc = (ScrollView) findViewById(R.id.listcontainer);
        sc.removeView(this.tblContainer);

        getSong();

        sc.addView(this.tblContainer);
        TextView txt = (TextView) findViewById(R.id.pagedesc);
        txt.setText((this.page+1) + " / " + this.totalPage);


    }else if(R.id.next == layoutId){
        if(this.page < this.totalPage){
            page++;
        }

        ScrollView sc = (ScrollView) findViewById(R.id.listcontainer);
        sc.removeView(this.tblContainer);

        getSong();

        sc.addView(this.tblContainer);

        TextView txt = (TextView) findViewById(R.id.pagedesc);
        txt.setText((this.page+1) + " / " + this.totalPage);
    }
}

protected Dialog onCreateDialog(int id){

    LayoutInflater inflater = (LayoutInflater) this.getSystemService(LAYOUT_INFLATER_SERVICE);
    View layout = inflater.inflate(R.layout.playlist_popup, (ViewGroup) findViewById(R.id.layout_root));

    ImageButton ib0 = (ImageButton) layout.findViewById(R.id.back);
    ib0.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View arg0) {
            // TODO Auto-generated method stub
            selectedItem.setBackgroundDrawable(rowColor);
            dismissDialog(0);
        }
    });

    ImageButton ib1 = (ImageButton) layout.findViewById(R.id.del);
    ib1.setOnClickListener(new View.OnClickListener(){
        public void onClick(View arg0){
            Toast.makeText(getRef(), selectedItemIndex, 60000);
            HttpClient ajax = new DefaultHttpClient();
            HttpGet httpGet = new HttpGet(serverAddress + "/index.php?m=playlist&a=del&room=" + roomName + "&to=" + playerUsername + 
                    "&username=" + layoutUsername + "&id=" + selectedItemIndex);

            //Functions.showAlert(getRef(), serverAddress + "/index.php?m=playlist&a=del&room=" + roomName + "&to=" + playerUsername + 
            //      "&username=" + layoutUsername + "&id=" + selectedItemIndex);
            try {
                ajax.execute(httpGet);
            } catch (ClientProtocolException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

            selectedItem.setBackgroundDrawable(rowColor);

            dismissDialog(0);

            // ScrollView sc = (ScrollView) findViewById(R.id.listcontainer);
            // sc.removeView(tblContainer);
            // sc.removeAllViewsInLayout();
            // sc.destroyDrawingCache();
            // tblContainer.removeAllViewsInLayout();
            // setContentView(R.layout.playlist);
            // setContentView(R.layout.playlist);
            // drawLayout(false);
            Intent newActivity = new Intent();
            newActivity.putExtra("room_name", roomName);
            newActivity.putExtra("server_address", serverAddress);
            newActivity.putExtra("player_username", playerUsername);
            newActivity.putExtra("layoyt_username", layoutUsername);
            newActivity.setClass(getRef(), Playlist.class);
            startActivity(newActivity);
            finish();

            // getSong();
            // sc = (ScrollView) findViewById(R.id.listcontainer);
            // tblContainer = new TableLayout(getRef());
            // sc.addView(tblContainer);
        }
    });

    ImageButton ib2 = (ImageButton) layout.findViewById(R.id.top);
    ib2.setOnClickListener(new View.OnClickListener(){
        public void onClick(View arg0){
            Toast.makeText(getRef(), selectedItemIndex, 60000);
            HttpClient ajax = new DefaultHttpClient();
            HttpGet httpGet = new HttpGet(serverAddress + "/index.php?m=playlist&a=top&room=" + roomName + "&to=" + playerUsername + 
                    "&username=" + layoutUsername + "&id=" + selectedItemIndex);

            try {
                ajax.execute(httpGet);
            } catch (ClientProtocolException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

            selectedItem.setBackgroundDrawable(rowColor);

            dismissDialog(0);

            ScrollView sc = (ScrollView) findViewById(R.id.listcontainer);
            sc.removeView(tblContainer);
            tblContainer = new TableLayout(getRef());

            getSong();

            sc.addView(tblContainer);
        }
    });


    layout.setLayoutParams(new LayoutParams(170, 90));
    layout.setMinimumWidth(0);

    AlertDialog.Builder builder = new AlertDialog.Builder(this);
    builder.setView(layout);
    AlertDialog alertDialog = builder.create();
    alertDialog.setCancelable(true);
    alertDialog.setOnCancelListener(new OnCancelListener(){

        @Override
        public void onCancel(DialogInterface arg0) {
            // TODO Auto-generated method stub
            selectedItem.setBackgroundDrawable(rowColor);
            dismissDialog(0);
        }});

    return alertDialog;
}

public class SideMenuClick implements View.OnClickListener{

    @Override
    public void onClick(View arg0) {
        // TODO Auto-generated method stub
        // changeList();
        changeActivity(arg0.getId());
    }

}

}
1个回答

1
在Android中的视图具有Invalidate和PostInvalidate方法,它们会在某个时刻调用OnDraw方法。
因此,如果您已经使用某些数据填充了一个View,则可以通过调用这两个方法之一使其重新绘制自身。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接