我有这个按钮代码,如下所示,但它只有一个按钮和一个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);
}
}
答案 0 :(得分: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
}
});