1

对,我在这个项目中有一个计数器,它所有的工作,但我试图在屏幕底部放置另一个计数器,它会做同样的事情,但会在另一个计数上工作。所以会有两个计数器计数不同,但由于应用程序保存数据,我无法弄清楚如何去做。

xml代码:

<TextView
    android:id="@+id/TextViewCount"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_centerHorizontal="true"
    android:layout_centerVertical="true"
    android:text="@string/hello_world" />

<Button
    android:id="@+id/ButtonCount"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_above="@+id/TextViewCount"
    android:layout_alignRight="@+id/TextViewCount"
    android:layout_marginBottom="22dp"
    android:text="Count" />

主要代码:

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

0 回答 0