0

我得到了如下所示的按钮代码,但它只有一个按钮和一个 textview 我的项目需要的意思是需要有两个或多个按钮将计入单独的系统但使用相同的代码。将包括下面的主要代码,但任何在系统中添加更多功能的帮助都非常受欢迎!

主要代码

package com.example.counter;

import android.app.Activity;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;


public class MainActivity extends Activity {
    // Private member field to keep track of the count
    private static int mCount = 0;

    private TextView countTextView;
    private Button countButton;
    public static final String PREFS_NAME = "com.example.myApp.mCount";
    private SharedPreferences settings = null;
    private SharedPreferences.Editor editor = null;

    /** ADD THIS METHOD **/
    @Override
    public void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);  
      setContentView(R.layout.main);
      countTextView = (TextView) findViewById(R.id.TextViewCount);
      countButton = (Button) findViewById(R.id.ButtonCount);

      countButton.setOnClickListener(new View.OnClickListener() {
          public void onClick(View v) {
              mCount++;
              countTextView.setText("Count: " + mCount);
              editor = settings.edit(); 
              editor.putInt("mCount", mCount);
              editor.commit();
          }
      });
    settings = getSharedPreferences(PREFS_NAME, MODE_PRIVATE);


     }

    @Override
    public void onPause() {
      super.onPause();  
    }

    @Override
    public void onResume() {
      super.onResume();  
      mCount = settings.getInt("mCount", 0);
      countTextView.setText("Count: " + mCount);
    }
    }
4

1 回答 1

0

在您的 xml 中创建 3 个按钮,假设它们的 id 是 ButtonCount、ButtonCount2 和 ButtonCount3 以及被声明的 countButton2 和 countButton3。然后将它们初始化如下:

  countButton = (Button) findViewById(R.id.ButtonCount);

  countButton.setOnClickListener(new View.OnClickListener() {
      public void onClick(View v) {
          mCount++;
          countTextView.setText("Count: " + mCount);
          editor = settings.edit(); 
          editor.putInt("mCount", mCount);
          editor.commit();
      }
  });

  countButton2 = (Button) findViewById(R.id.ButtonCount2);

  countButton2.setOnClickListener(new View.OnClickListener() {
      public void onClick(View v) {
          //do something here
      }
  });

  countButton3 = (Button) findViewById(R.id.ButtonCount3);

  countButton3.setOnClickListener(new View.OnClickListener() {
      public void onClick(View v) {
          //do something else here
      }
  });
于 2013-02-19T20:17:38.593 回答