0
package com.example.shared;

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

public class MainActivity extends Activity {
Button bshared;
TextView tv;
String x;
SharedPreferences pref;
Editor edit;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    bshared = (Button) findViewById(R.id.bshared);
    tv = (TextView) findViewById(R.id.tv);

    tv.setText(x);
    bshared.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View v) {
                  pref=getApplicationContext().getSharedPreferences("details",1);
            edit = pref.edit();
            edit.clear();
            edit.putString("name", "These are new values");
            edit.commit();
            x = pref.getString("name", "");

        }
    });

}
}

当我单击按钮时,textview 的值必须更改为“这些是新值”,但这并没有发生。有人可以帮我找出我的错误吗?

4

2 回答 2

2

textview是在更改文本之前设置文本。所以它不会反映在textview. onclick更改字符串的值后,将此行添加到方法的最后一个。

tv.setText(x);

编辑:

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    bshared = (Button) findViewById(R.id.bshared);
    tv = (TextView) findViewById(R.id.tv);

    pref=getApplicationContext().getSharedPreferences("details",1);
    x = pref.getString("name", "");

    tv.setText(x);
    bshared.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View v) {
            edit = pref.edit();
            edit.clear();
            edit.putString("name", "These are new values");
            edit.commit();
            x = pref.getString("name", "");
            tv.setText(x);


        }
    });

}
}
于 2012-09-20T06:19:49.613 回答
2

在单击方法中,您必须将值设置为 textview,如下面的代码。

pref=getApplicationContext().getSharedPreferences("details",1);
x = pref.getString("name", "");
tv.setText(x);
bshared.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View v) 
        {
            edit = pref.edit();
            edit.clear();
            edit.putString("name", "These are new values");
            edit.commit();
            x = pref.getString("name", "");
            tv.setText(x);
        }
    });
于 2012-09-20T06:25:08.840 回答