Добрый день, у меня есть Андроид Студио 2.3.3 и телефон в каковом я делаю доказательства - Motorola Moto G первое поколение; у которого есть Android 5.1, мой app, который является простым счетчиком, я это сделал для Android 5.0 или последующие. Проблема состоит в том, что оно я не функционирует, метод показывать (), нажав кнопки, которые выполняют этот метод, задерживается app на моем телефоне.
Код activity_main.xml:
<TextView
android:id="@+id/displaycontador"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_marginLeft="8dp"
android:layout_marginRight="8dp"
android:layout_marginTop="10dp"
android:text="0"
android:textAppearance="@android:style/TextAppearance.Large"
android:textColor="@android:color/black"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent"
android:gravity="center"/>
<Button
android:id="@+id/botonsuma"
android:layout_width="91dp"
android:layout_height="78dp"
android:layout_marginLeft="135dp"
android:layout_marginTop="50dp"
android:background="@android:color/holo_green_light"
android:text="+"
android:textColor="@android:color/black"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintTop_toBottomOf="@+id/displaycontador"
android:onClick="suma"/>
<Button
android:id="@+id/botonresta"
android:layout_width="91dp"
android:layout_height="78dp"
android:layout_marginLeft="135dp"
android:layout_marginTop="70dp"
android:background="@android:color/holo_red_light"
android:text="-"
android:textColor="@android:color/black"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintTop_toBottomOf="@+id/botonsuma"
android:onClick="resta"/>
<Button
android:id="@+id/botonreset"
android:layout_width="66dp"
android:layout_height="47dp"
android:layout_marginBottom="10dp"
android:layout_marginLeft="10dp"
android:background="@android:color/holo_orange_light"
android:text="Reset"
android:textColor="@android:color/black"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
android:onClick="reset"/>
Код MainActivity.java:
package com.example.gustavo.contador;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;
public class MainActivity extends Activity {
public int contador = 0;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void suma(View vista) {
contador++;
mostrar();
}
public void resta(View vista) {
contador--;
mostrar();
}
public void reset(View vista) {
contador = 0;
mostrar();
}
public void mostrar() {
TextView textor = new TextView(this);
textor = (TextView)findViewById(R.id.displaycontador);
textor.setText(contador);
}
}
Soluci¦n, ты должен обращать стоимость типа int в String:
TextView textor;
textor = (TextView) findViewById(R.id.displayContador);
textor.setText(String.valueOf(contador));
Когда ты делаешь:
TextView textor = new TextView(this);
textor = (TextView) findViewById(R.id.displayContador);
podr¦-схвати делать:
TextView textor = (TextView) findViewById(R.id.displayContador);
, Хотя я сомневаюсь в том, что ahà - ты неудачи.
то, что ты не можешь делать, состоит в том, чтобы перемещать целое число setText TextView, ты должен перемещать его текст. Чтобы не изменять тип счетчика ты можешь делать это as¦-:
textor.setText(""+contador);
ЗАМЕЧАЕТ: Pr¦xima раз, что ты задал вопрос, лучше, чтобы ты поместил c¦digo в текст и не в изображение, так как asà - мы сможем копировать это и выполнять мы c¦digo, чтобы видеть то, что он бьет козырем.
Прежде всего уверь, что TextView
с id displaycontador
находится внутри activity_main.xml
, так как, если он не существует, это может вызывать ошибку, позвонив método.
Ты Упоминаешь, о том, что, назвав этот método, закрывается твой aplicaci¦n:
public void mostrar(){
TextView textor = new TextView(this);
textor = (TextView)findViewById(R.id.displaycontador);
textor.setText(contador);
}
и ты получаешь следующее сообщение ошибки:
android.content.res. Resources $NotFoundException: Resource идентификация #0x
Aquà - у тебя есть 2 детали, первый состоит в том, что ты не нуждаешься instanciar в TextView:
TextView textor = new TextView(this);
это, потому что уже ты ищешь ссылку в layout:
textor = (TextView)findViewById(R.id.displaycontador);
и вторая деталь, которая вызывает ошибку:
textor.setText(contador);
после того, как старается определять целое число, вид старается искать элемент с id определенный в R.java, который не существует, из-за этого raz¦n ты должен заверять в том, что определяешь в setText () стоимость тип String:
textor.setText(String.valueOf(contador));
Для того, чтобы у тебя не было проблем, método должен быть просто:
public void mostrar(){
TextView textor = (TextView)findViewById(R.id.displaycontador);
textor.setText(String.valueOf(contador));
}