【问题标题】:Cannot set Text无法设置文本
【发布时间】:2012-03-13 08:33:27
【问题描述】:

我需要用变量设置文本,但出现错误:

无法在原始类型 int 上调用 setText(String)

这是我的代码:

    public class CalcActivity extends Activity implements OnClickListener {
/** Called when the activity is first created. */
    private int mCount = 0;
    @Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

}
    public void onClick(View v) {
          // TODO Auto-generated method stub
    switch(v.getId())
          {
          case R.id.CountBtn:
               mCount++;
           R.id.TextViewCount.setText("You clicked " + mCount + "times");
           break;
          case R.id.ResetBtn:
           // Do something
           break;
          }
         }  
}

【问题讨论】:

    标签: android string button int settext


    【解决方案1】:

    您不能在 id (R.id.TextViewCount) 上调用 setText,因为它是一个 int,但在视图上。替换这个:

    R.id.TextViewCount.setText("You clicked " + mCount + "times");
    

    用这个:

    TextView v = (TextView)findViewById(R.id.TextViewCount);
    v.setText("You clicked " + mCount + "times");
    

    【讨论】:

      【解决方案2】:
      public class StackActivity extends Activity implements OnClickListener {
          /** Called when the activity is first created. */
          int mCount = 0;
          TextView t;
      
          @Override
          public void onCreate(Bundle savedInstanceState) {
              super.onCreate(savedInstanceState);
              setContentView(R.layout.main);
              Button b = (Button) findViewById(R.id.button);
              t = (TextView) findViewById(R.id.textview);
                 b.setOnClickListener(this);
      
      }
      public void onClick(View v) {
              // TODO Auto-generated method stub
          switch(v.getId())
            {
            case R.id.button:
                 mCount++;
             t.setText("You clicked " + mCount + "times");
             break;
            case R.id.ResetBtn:
             // Do something
             break;
            }
           }  
          }
              }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2020-07-01
        • 2023-03-03
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-10-28
        • 2014-01-05
        • 2020-03-01
        相关资源
        最近更新 更多