Issue
I am trying to create an app to increase the value of a number on screen to the next number when the button is pressed. It is not working. I have given my Java and XML code below.
XML code:
<Button
android:id="@+id/button"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="250dp"
android:text="+" />
<TextView
android:id="@+id/textView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="50dp"
android:paddingLeft="200dp"
android:textSize="25sp"
android:text="0" />
Java code:
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
Button btn;
TextView txt;
protected int a = 1;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btn = (Button) findViewById(R.id.button);
txt = (TextView) findViewById(R.id.textView);
}
public void display(final int n) {
btn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
txt.setText(n);
}
});
}
public void increment(View view) {
a = a + 1;
display(a);
}
}
The button is unreactive.
Solution
When you click the button, increase the value of a
. Then pass the a
to display method. Finally display the value to textView
.
public class MainActivity extends AppCompatActivity {
Button btn;
TextView txt;
protected int a = 1;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btn = (Button) findViewById(R.id.button);
txt = (TextView) findViewById(R.id.textView);
btn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
a++;
display(a);
}
});
}
public void display(int n) {
txt.setText("" + n);
//txt.setText(n);
}
}
Answered By - AI.
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.