gpt4 book ai didi

java - Android基本,,无缘无故的错误..

转载 作者:行者123 更新时间:2023-12-01 13:32:45 24 4
gpt4 key购买 nike

我在 android 模拟器中运行它时遇到错误..之后立即

我添加:

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

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

需要帮助,我想让 TextView 随着评级栏的变化而变化

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

最佳答案

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

您已正确初始化 View 。因此,清理并构建您的项目一次并运行应用程序。

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 值)的资源。如果没有找到,您将收到 ResourceNotFOoundException

你可以看到下面的内容

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

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

关于java - Android基本,,无缘无故的错误..,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21472302/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com