在安卓中动态更新TextView

14

我对安卓开发还比较新手。请问有哪些相关API可以动态更新TextView(或整个屏幕)呢?

举个例子:我正在开发一个搜索应用,需要实时显示结果,而不是等待所有结果都找到后再一次性展示。


如果您不希望搜索阻塞主应用程序的执行,那么您需要在单独的线程中完成搜索。然后,使用定时器定期更新一个容器,添加新的TextView对象。您可以创建一个空的线性布局,并定期调用搜索线程以查看其结果并将其添加到线性布局中。 - DeliveryNinja
你的问题还没有得到解答吗? - winklerrr
5个回答

26

有几个步骤,你没提及你对每一步的了解程度。

假设你的UI初始结构在res/layout中定义,并且其中包含一个TextView,在你的Activity中:

public void updateTextView(String toThis) {
    TextView textView = (TextView) findViewById(R.id.textView);
    textView.setText(toThis);
}

3
如果您有新的文本要设置到 TextView 中,只需调用 textView.setText(newText) 方法,其中 newText 是更新后的文本。每当 newText 发生更改时,请调用此方法。这是您想要的吗?

谢谢,嗯...那在某种程度上回答了我的问题...但我需要保留旧数据,除了新数据之外...我该怎么做...应该使用列表视图吗... - prash
为了跟踪旧数据,您可以使用textView.getText()。首先:CharSequence old = textView.getText();,然后将旧数据和新数据连接起来并将其设置回TextViewtextView.setText(old + " " + new); - winklerrr

2
如果你在另一个线程中,确保在UI线程内更新textview。
private void updateTextView(final String s) {
    MainActivity.this.runOnUiThread(new Runnable() {
        @Override
        public void run() {
            TextView tv= (TextView) findViewById(R.id.tv);
            tv.setText("Text = "+s);
        }
    });

}

1

首先,你需要一个列表视图,因此

private volatile ArrayList<String>      searchResults;
ListView searchList = (ListView) findViewById(R.id.listYOURLISTVIEW);
listAdapter = new ArrayAdapter<String>(this, R.layout.blacklist, R.id.list_content, searchResults);  //blacklist is a layout to paint the fonts black
searchList.setAdapter(listAdapter);

这里有一些可能会有所帮助的东西。

private Thread refreshThread;
private boolean isRefreshing = false;

private void reinitializeRefreshThread()
{
    if (!refreshThread.equals(null)) refreshThread.stop();
    Log.d(LOGTAG+"::reinitializeRefreshThread()", "Creating new thread!\n");
    isRefreshing = true;
    refreshThread = (new Thread(new Runnable()
    {
        public void run()
        {
            Looper.prepare();
            while (isRefreshing)
            {
                //GRAB YOUR SEARCH RESULTS HERE
                //make sure the methods are synchronized
                //maybe like 
                String[] results = grabResults(); //doesn't need to be synchronized
                addResultList(results);

                Message message = myHandler.obtainMessage();
                myHandler.sendMessage(message);
                try
                {
                    Thread.sleep(2000);
                } catch (InterruptedException e)
                {
                    e.printStackTrace();
                }
                Log.d(LOGTAG+"->refreshThread", "Refresh finished!\n");
            }
        }
    }));
    Log.d(LOGTAG+"::reinitializeRefreshThread()", "Refresh thread started!\n");
    refreshThread.start();
}

final Handler myHandler = new Handler() 
{
    public void handleMessage(android.os.Message msg)   
    {
        listAdapter.notifyDataSetChanged();
    }; 
};

在哪里

public synchronized void addResultList(String[] results)
{
    // remove the whole list, repopulate with new data
    searchResults.clear();
    for (int i = 0; i < results.length; i++)
    {
        addResult(results[i]);
    }
}

private synchronized void addResult(CharSequence result)
{
    if (!searchResults.contains(result.toString()))
        searchResults.add(result.toString());
    else
        Toast.makeText(getApplicationContext(), "Result " + result.toString() + " was already on the list!", Toast.LENGTH_SHORT).show();
}

所有这些都是线程安全的,这意味着它将允许您通过向主线程发送消息来从其他线程“更改”GUI,以便UI进行更新。正如您所看到的,refreshThread更新搜索集合(确保该方法已同步),然后通知主(UI)线程更新列表。
您可能也会发现这很有用。
searchList.setOnItemClickListener(new AdapterView.OnItemClickListener()
    {
        public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3)
        {
            listIndex = arg2;
            selectedItem = (String) searchList.getItemAtPosition(listIndex);
            Toast.makeText(getApplicationContext(), "Result[" + listIndex + "] " + selectedItem + " selected!", Toast.LENGTH_SHORT).show();
        }
    });

可能会有一些需要处理的细节,比如您需要初始化 listIndex 和 selectedItem 或者直接抛弃它们,但总的来说,这对我在类似的情况下解决了问题(我有一个后台线程,随着时间推移填充一个列表,添加新条目)

希望能对您有所帮助 :)


1
尝试这个。
TextView textView = (TextView)findViewById(R.id.textViewID);
textView.setText("The test you need");
view.invalidate();  // for refreshment

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