我正在编写我的第一个 Android 应用程序。
我想在 TextView
上设置文本。
(我已经在这里搜索并发现了,该怎么做......但它仍然不起作用)
你知道,问题是什么吗?
这是我的 Java 代码。
package com.example.randomcraps;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.widget.TextView;
import com.example.*;
public class MainActivity extends Activity {
TextView text = (TextView) findViewById(R.layout.number);
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
public void getRandomNumber(){
int i;
double savePoint;
savePoint = Math.random();
savePoint = savePoint*100+1;
i = (int)savePoint;
text.setText(i);
}
}
这是我的 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" >
<Button
android:id="@+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentRight="true"
android:layout_alignParentTop="true"
android:layout_marginTop="26dp"
android:text="@string/Button1"
android:onClick="getRandomNumber" />
<TextView
android:id="@+id/number"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:text="@string/RandomNumber" />
</RelativeLayout>
最佳答案
更改为
TextView text;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
text = (TextView) findViewById(R.id.number); // id of textview in activity_main.xml
}
findViewById
查找具有当前膨胀布局中提到的 id 的 View 。因此,您需要为 Activity 设置布局,然后初始化您的 View 。
也改变
text.setText(i);
// looks for a resource with the id mentioned if not found you get ResourceNotFoundException
到
text.setText(String.valueOf(i));
// int i; i is an int value. Use String.valueOf(intvalue)
编辑:
您的方法签名不同。应该是
public void getRandomNumber(View V){ // missing View as param
... //rest of the code
}
因为你有
android:onClick="getRandomNumber"
引用文档
public static final int onClick
单击 View 时要在该 View 的上下文中调用的方法的名称。此名称必须 对应于只采用一个 View 类型参数的公共(public)方法。例如,如果指定 android:onClick="sayHello",则必须声明上下文(通常是 Activity )的 public void sayHello(View v) 方法。
关于android - TextView 失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19933844/