利用fragment和ViewPager实现了四个界面,各个界面的事件响应都写在fragment的onActivityCreated()方法里
“我的”界面布局文件放置了一个ImageView(头像)一个Button,布局文件里设置ImageView暂时没有图片,点击按钮跳转修改头像界面
修改头像界面放置九个头像和一个确认按钮,点击头像后头像保存在SharedPreferences里("head",R.drawable.head1)
用户注册账号时,默认头像为head1,并保存在SharedPreferences里,之后可进行修改。
“我的”界面读取SharedPreferences里的数据,利用setImageResource()设置显示图片。
修改头像后我利用Toast显示当前SharedPreferences的head是已经修改的,但imageView还是显示head1,怎么弄都不变,这是怎么回事呢?
// mine_fragment部分代码
SharedPreferences sp = getActivity().getSharedPreferences("LoginSp", Context.MODE_PRIVATE);
// Toast.makeText(getContext(),"head="+sp.getInt("head",0),Toast.LENGTH_SHORT).show();
ImageView ivhead = getActivity().findViewById(R.id.mine_imageViewHead);
ivhead.setImageResource(0); //清除缓存
ivhead.setImageResource(sp.getInt("head",0));
// 修改信息界面部分代码
// 点击选择图片
int[] HeadResource = {R.drawable.head1,R.drawable.head2,R.drawable.head3,R.drawable.head4,R.drawable.head5,
R.drawable.head6,R.drawable.head7,R.drawable.head8,R.drawable.head9}; // 图片id
SharedPreferences sp = getActivity().getSharedPreferences("LoginSp", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sp.edit();
editor.putInt("head",HeadResource[i]); // 这里是一个循环内部,表示选中了第i个图片
editor.commit();
// 点击确认修改的按钮
// 有一系列修改数据库的代码,最后返回MainActivity
Intent intent = new Intent(this, MainActivity.class);
startActivity(intent);
要是在点击提交修改里加上
LayoutInflater inflater = LayoutInflater.from(ModifyInformationActivity.this);
View layout = inflater.inflate(R.layout.fragment_mine,null);
ImageView mine_head = (ImageView) findViewById(R.id.mine_imageViewHead);
mine_head.setImageResource(sp.getInt("head",0));
那么点击按钮后app就直接停止运行了,所以我就又去掉了。
我想知道我这种情况ImageView应该怎样修改呢?