2013-08-21 171 views
4

我知道有很多类似的线程,但我已经通过他们,仍然无法找出问题。我的程序到达处理程序,但它总是返回catch消息“消息未处理”。android TextView setText不工作

我宣布TextView的private TextView chatbox;

下的onCreate我:

public void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.main); 
     setUpViews(); 
     setUpListener(); 
    } 

其中setUpViews()片段的样子:

private void setUpViews() { 
    chatbox = (TextView) findViewById(R.id.chatbox); 
    } 

处理程序:

public Handler mHandler = new Handler(Looper.getMainLooper()){ 
     @Override 
     public void handleMessage(Message msg){ 
      try{ 
       chatbox.setText("Got it!"); 
      }catch(Exception e){ 
       Log.i("MYLOG", "Message was not handled."); 
      } 

     } 
    }; 

在main.xml文件中的代码片段:

<TextView 
     android:id="@+id/chatbox" 
     android:layout_width="200dp" 
     android:layout_height="200dp" 
     android:layout_centerHorizontal="true" 
     android:layout_centerVertical="true" 
     android:textAppearance="?android:attr/textAppearanceLarge" /> 
+0

你有什么异常? – Nick

回答

0

我希望你的处理程序在UI线程中运行。也请尝试这样做:将字符串分配给一个变量,并使用该变量,因为它需要charsequence。

String temp = "Got it!"; 
chatbox.setText(temp); 
-1

你发送了一条消息吗?例如: :

  Message message=new Message(); 
     message.what=1; 
     mHandler.sendMessage(message); 
0

就像这样没关系!

private void setUpViews() { 
    chatbox = (TextView) findViewById(R.id.chatbox); 
    chatbox.setText("Got it!"); 
} 
1

你还没有给我们太多的去继续。

你应该看看的异常堆栈跟踪,而不是打印一个消息到控制台:e.printStackTrace();

但是,从这里,如果我猜,它看起来像你要么设置TextView的文本关闭主线程或 - 并且根据您发布的内容看似不太可能 - 您的TextView尚未设置,并且您有空指针异常。

33

如果一些可怜的灵魂谷歌在未来的这个问题后,我终于找到了问题。我有多个片段,其中一个用于ViewPager中的每个选项卡,其中TextView在两个片段中具有相同的相同ID,因此存在冲突。我没有意识到我有相同的ID,所以一切都很好,没有错误信息,但文本没有改变。只需更改ID。

+0

很难找出这个问题。这应该标记为已接受的答案。 –

+0

我遇到过同样的问题。并想知道为什么它应该是唯一的,如果不同的页面有相同的布局。在我的情况设置不同的ID没有工作,但textView.requestLayout()做的事情, 也为我工作: textView.setVisibility(View.INVISIBLE); textView.setVisibility(View.VISIBLE); –

+0

是的,它不好。我也面临同样的问题。 –