如何解决退出AlertDialog后更新TextView
我有一个活动(称为DiscoverActivity),其距离为TextViews
:
用户单击距离后,将打开以下AlertDialog
:
现在,我喜欢这样,一旦用户单击Done
按钮,它将关闭AlertDialog
并更新TextView
上的DiscoverActivity
。
如何更新?
现在,当我单击“完成”并关闭时,它显示相同的值,直到我在活动之间移动并返回为止。
我的“完成”按钮上的代码:
Btn_Done.setOnClickListener( view -> {
SharedPreferences.Editor editor = context.getSharedPreferences( AppConstants.PREFS_NAME,MODE_PRIVATE ).edit();
editor.putInt( AppConstants.PREF_RADIUS,seekbar.getProgress() );
editor.apply();
dialog.dismiss();
} );
这就是我在onCreate中所说的:
SharedPreferences dist_settings = getSharedPreferences( AppConstants.PREFS_NAME,MODE_PRIVATE );
nearMeRadius = dist_settings.getInt( AppConstants.PREF_RADIUS,300 );
TextView tv_NearRadius = findViewById( R.id.tv_NearRadius );
tv_NearRadius.setText( getString( R.string.ActivityDiscover_NearMeRadius,nearMeRadius ) );
tv_NearRadius.setOnClickListener( v -> {
PopUps popUps = new PopUps();
popUps.popDistanceDialog( DiscoverActivity.this );
} );
解决方法
在刷新活动之前,任何包含共享首选项的方法都将只起作用一次,但是当您关闭对话框时,活动不会刷新。
所以,您有2个选择
- 在单击警报对话框中的完成按钮以消除疑难解答后,寻找一种刷新活动的方法。
- 或者您可以将所有内容保持不变,但是当用户单击“完成”按钮时,它将更改活动的文本。
要做第二点的感觉,您可以轻松地做到:
Btn_Done.setOnClickListener( view -> {
SharedPreferences.Editor editor = context.getSharedPreferences( AppConstants.PREFS_NAME,MODE_PRIVATE ).edit();
editor.putInt( AppConstants.PREF_RADIUS,seekbar.getProgress() );
editor.apply();
TextView txtView = (TextView) ((Activity)context).findViewById(R.id.text); // this points to the textview in the activity you want to change
txtView.setText("Hello");
dialog.dismiss();
} );
,
定义接口,
interface SomeInfy(){
void updateText(String text);
}
实现与DiscoveryActivity的接口,并覆盖updateText()
@Override
public void updateText(String someText){
tv_NearRadius.setText(someText);
}
现在, 只需将接口从您的DiscoveryActivity传递给PopUps类
tv_NearRadius.setOnClickListener( v -> {
PopUps popUps = new PopUps();
popUps.popDistanceDialog( DiscoverActivity.this,DiscoverActivity.this);
} );
class PopUps{
public void popDistanceDialog( Context context,SomeInfy infy ){
// whatever btnDone operation...
Btn_Done.setOnClickListener( view -> {
SharedPreferences.Editor editor = context.getSharedPreferences( AppConstants.PREFS_NAME,seekbar.getProgress() );
editor.apply();
dialog.dismiss();
//
infy.updateText("whatever");
} );
}
,
或更残酷,但也可以很方便。您的对话框具有getActivity()方法。
在解雇之前和保存您的首选项之后,请在对话框中使用getActivity()方法。将其投放到您的活动中,然后更新您的编辑文本。
就像我说的那样,原始编程但可能适合 和项目的结构。
玩得开心。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。