I want to create button with text = \"SomeText\" on center of this button and \"0\" on right part of button. Where \"0\" is the Counter and when I click this button Counter++ i
There are several options.
Create a static variable:
private static int buttonClickCount = 0;
public void but1_Count(View v){
buttonClickCount++;
v.settext("Clicked " + buttonClickCount);
}
Create custom button by extending base button class and implement onClickListener:
public class MyButton extends Button implements View.OnClickListener {
private int counter = 0;
public MyButton(...){
this.setOnClickListener(this);
}
public void onClick(View v) {
counter++;
v.setText("Clicked"+counter);
}
}
Extract value from clicked button, parse it as int, and increment:
public void but1_count(View v){
int curr = Integer.parseInt(v.getText().toString());
v.setText(""+curr);
}
private static int counter = 0; button1.setOnClickListener(new OnClickListener(){ @Override onClick(View v){ counter += 1 button.setText("Some text" + counter); } });
Try this way,hope this will help you to solve your problem.
main.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:gravity="center">
<Button
android:id="@+id/btnCounter"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Some Text"/>
</LinearLayout>
strings.xml
<string name="button_text">Some Text %1d</string>
MyActivity.java
public class MyActivity extends Activity{
private Button btnCounter;
private int count;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
btnCounter = (Button) findViewById(R.id.btnCounter);
btnCounter.setText(String.format(getString(R.string.button_text),count));
btnCounter.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
count++;
btnCounter.setText(String.format(getString(R.string.button_text),count));
}
});
}
}