我是一名新的 Android 应用程序开发人员,我想要一个通过单击按钮来更改 textview 小部件的应用程序。Eclipse 不会抛出错误,但 Android 模拟器会抛出错误。
这是我的代码:
import android.os.Bundle;
import android.app.Activity;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageButton;
import android.widget.TextView;
public class MainActivity extends Activity {
int stringIdList[] = { R.string.text1, R.string.text2, R.string.text3,
R.string.text4 };
int stringListCounter = 0;
TextView text122;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ImageButton next = (ImageButton) findViewById(R.id.Next);
ImageButton previous = (ImageButton) findViewById(R.id.Previous);
text122 = (TextView) findViewById(R.id.Text00);
next.setOnClickListener((OnClickListener) this);
previous.setOnClickListener((OnClickListener) this);
}
public void onClick(View v) {
int id = v.getId();
if (id == R.id.Next && stringListCounter < stringIdList.length - 1) {
stringListCounter++;
} else if (id == R.id.Previous && stringListCounter > 0) {
stringListCounter--;
}
text122.setText(stringIdList[stringListCounter]);
}
}
和我的布局 xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context=".MainActivity" >
<TextView
android:id="@+id/Text00"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/hello_world" />
<ImageButton
android:id="@+id/Next"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/Text00"
android:layout_marginLeft="119dp"
android:layout_marginTop="268dp"
android:layout_toRightOf="@+id/Text00"
android:contentDescription="dgdfgd"
android:src="@drawable/ic_launcher" />
<ImageButton
android:id="@+id/Previous"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="64dp"
android:layout_marginTop="127dp"
android:layout_toRightOf="@+id/Text00"
android:contentDescription="dsfsf"
android:src="@drawable/ic_launcher" />
</RelativeLayout>
我的 logcat 错误包含
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.nar.yeni/com.nar.yeni.MainActivity}: java.lang.ClassCastException: com.nar.yeni.MainActivity cannot be cast to android.view.View$OnClickListener