无论是在模拟器上还是在手机上,只要按下按钮,应用程序就会崩溃。我使用的是Android Studio 3.1.2。我怎么解决它,我已经尝试了大多数其他解决方案,但在这里同样的问题,但不起作用
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void onButton(View v) {
display(1);
}
public void display(int n) {
TextView qt = findViewById(R.id.quantity;
qt.setText(n);
}
}
下面是它的xml代码
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<TextView
android:id="@+id/heading"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="30dp"
android:text="Quantity"
android:textAllCaps="true"
android:textSize="32sp" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="123dp"
android:id="@+id/quantity"
android:text="0"
android:textAllCaps="true"
android:textSize="32sp" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="ORDER"
android:textSize="32sp"
android:layout_centerHorizontal="true"
android:layout_marginTop="215dp"
android:onClick="onButton"/>
</RelativeLayout>
发布于 2018-06-10 00:34:36
Convert String to Integer
qt.setText.String.valueOf(n));
发布于 2018-06-10 00:32:39
执行以下操作:
qt.setText(String.valueOf(n));
// or use qt.setText("" + n);
而不是
qt.setText(n);
这是因为
setText(@StringRes int resid)
将参数作为"int resId“,它期望它是来自Strings.xml文件的字符串值的id。但这里您希望在文本视图中显示"int“值,因此您需要使用重载方法:
setText(CharSequence text)
方法,并将int值转换为字符串。
String.valueOf(n) //or by ("" + n)
发布于 2018-06-10 00:37:10
更改此设置:
public void display(int n) {
TextView qt = findViewById(R.id.quantity;
qt.setText(n);
}
要这样做:
public void display(int n) {
TextView qt = findViewById(R.id.quantity); //add closing bracket
qt.setText("" + n); //makes 'n' a string
}
https://stackoverflow.com/questions/50776340
复制相似问题