在Android操作栏中重置计数器按钮

时间:2013-09-05 12:22:42

标签: java android

构建一个小型点按计数器应用。我希望操作栏中的“刷新”按钮将textView重置重置为零。

public class MainActivity extends Activity {

int counter;
Button add, sub, refresh; // Tried to do this with refresh
TextView display;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    counter = 0;
    add = (Button) findViewById(R.id.buttonAdd);
    sub = (Button) findViewById(R.id.buttonSub);
    display = (TextView) findViewById(R.id.textView);

    add.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View view) {
            counter++;
            display.setText("Amount: " + counter);
        }
    });

    sub.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View view) {
            counter--;
            display.setText("Amount: " + counter);
        }
    });
}

我尝试了几件事而没有什么

ActionBar Item

2 个答案:

答案 0 :(得分:0)

在xml布局(my_layout.xml)中:

<Button
     android:id="@+id/button"
     android:layout_height="wrap_content"
     android:layout_width="wrap_content"
     android:text="reset counter"/>

<TextView
     android:id="@+id/textView"
     android:layout_height="wrap_content"
     android:layout_width="wrap_content"
     android:text="5" />

在您的活动中:

public class MyActivity extends Activity {
     //your counter variable
     int counter = 0;
     protected void onCreate(Bundle icicle) {
         super.onCreate(icicle);

         setContentView(R.layout.my_layout);

         final TextView textView = (TextView) findViewById(R.id.textView);
         final Button button = (Button) findViewById(R.id.button);
         button.setOnClickListener(new View.OnClickListener() {
             public void onClick(View v) {
                  counter = 0;
                  textView.setText(counter+"");
             }
         });
     }
 }

答案 1 :(得分:0)

一个活动在其onCreateOptionsMenu()方法中填充ActionBar。

只需覆盖onCreateOptionsMenu:

@Override

public boolean onCreateOptionsMenu(Menu.       
menu){

MenuInflater inflater = getMenuInflater();

inflater.inflate(R.menu.mainmenu, menu);

return true;
}

如果选择了ActionBar中的操作,则调用onOptionsItemSelected()方法。它接收所选操作作为参数。根据这些信息,您的代码可以决定做什么,例如:

@Override
public boolean onOptionsItemSelected(MenuItem item) 
{
    switch (item.getItemId()) {
    case R.id.menuitem1:
        Toast.makeText(this, "Menu Item 1 selected", Toast.LENGTH_SHORT)
        .show();
        break;
    case R.id.menuitem2:
        Toast.makeText(this, "Menu item 2 selected", Toast.LENGTH_SHORT)
        .show();
        break;

    default:
        break;
    }

    return true;
}