Android基本,,错误无缘无故..

时间:2014-01-31 04:16:10

标签: java android

我在android模拟器中运行它时出现错误..紧跟在

之后

我添加:

tv =(TextView)findViewById(R.id.textView1); //或//

rb =(ratingBar)findViewById(R.id.ratingBar1); //由于某些原因(没有其他代码)//

需要帮助,我想将TextView更改为RatingBar更改

XML     

<TextView
    android:id="@+id/textView1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentTop="true"
    android:layout_centerHorizontal="true"
    android:layout_marginTop="39dp"
    android:text=" " 
    android:textSize="50dp"/>

<RatingBar
    android:id="@+id/ratingBar1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentBottom="true"
    android:layout_centerHorizontal="true"
    android:layout_marginBottom="54dp"
    android:numStars="5"
    android:rating="0" />

的java

package com.examplef.rating;

import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.widget.RatingBar;
import android.widget.RatingBar.OnRatingBarChangeListener;
import android.widget.TextView;

public class MainActivity extends Activity {

TextView tv;
RatingBar rb;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    tv = (TextView) findViewById(R.id.textView1);
    rb = (RatingBar) findViewById(R.id.ratingBar1);

    rb.setOnRatingBarChangeListener(new OnRatingBarChangeListener(){

        @Override
        public void onRatingChanged(RatingBar ratingBar, float rating,
                boolean fromUser) {
            tv.setText(rb.getNumStars());

        }

    });
}

}

其中一个logcat说:

: E/AndroidRuntime(2014): java.lang.RuntimeException: 
Unable to start activity          
ComponentInfo{com.examplef.rating/com.examplef.rating.MainActivity}:
java.lang.ClassCastException: android.widget.RatingBar cannot be cast
toandroid.widget.TextView

1 个答案:

答案 0 :(得分:1)

Caused by: java.lang.ClassCastException: android.widget.RatingBar cannot be cast to android.widget.TextView

您已正确初始化视图。所以清理并构建项目一次并运行应用程序。

rb.getNumStars()会返回int

http://developer.android.com/reference/android/widget/RatingBar.html#getNumStars()

public int getNumStars ()

Added in API level 1
Returns the number of stars shown.

Returns
The number of stars shown.

所以改为

  tv.setText(String.valueOf(rb.getNumStars()));

setText查找id为int值的资源。如果找不到,则会获得ResourceNotFOundException

您可以看到以下

public final void setText (int resid) // what you have

public final void setText (CharSequence text) // what you need