如何刷新或更新片段UI [英] How to Refresh or Update Fragment UI
问题描述
我正在使用Bundle将数据通过Activity传递到Fragment,Bundle从计数器中获取其值,计数器基于Thread更新其值.
I am Passing Data through Activity to Fragment using Bundle, Bundle getting it's value from counter, Counter updating it's value base on Thread.
我能够在Fragment中获取数据,但是Fragment的UI仅在Fragment Transaction上更新,所以问题是
I was able to get data in Fragment but UI of Fragment only Updating on Fragment Transaction, so question is
我如何实时更新片段Ui
代码如下:
int i=0;
Sbundle = new Bundle();
thread = new Thread() {
@Override
public void run() {
try {
while (!thread.isInterrupted()) {
Thread.sleep(1000);
runOnUiThread(new Runnable() {
@Override
public void run() {
i++;
Sbundle.putString("speed", String.valueOf(i) );
}
});
}
} catch (InterruptedException e) {
}
}
};
thread.start();
}
片段交易onclick:
Fragment Transaction onclick :
public void onClick(View v) {
speedFragment = new SpeedFragment();
speedFragment.setArguments(Sbundle);
RoboActivity activity = MainActivity.this;
if (!isFinishing() && !isDestroyed()) {
FragmentTransaction ft = activity.getFragmentManager()
.beginTransaction();
ft.replace(R.id.fragment_container, speedFragment);
ft.detach(speedFragment).attach(speedFragment).commit();
}
}
在片段一侧:
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Bundle bundle = this.getArguments();
mySpeed = bundle.getString("speed");
}
推荐答案
您分割了哪些UI组件?如果您拥有例如TextView,而不仅仅是使用 yourTextView.setText(mySpeed)
当然,您需要先在片段中的 onCreate()
中绑定textView.还请记住,如果要在进入其他线程后更新UI元素,则应调用getActivity().runOnUiTnread(new Runnable(){....})
What UI components you fragment have?
if you have for example TextView than just use yourTextView.setText(mySpeed)
of course you need to bind the textView before in you onCreate()
in fragment.
Also remember if you want to update UI elements after you was in other Thread you should call getActivity().runOnUiTnread(new Runnable(){....})
示例:
private void toggleLoadingIndicator(boolean toShow) {
getActivity().runOnUiThread(new Runnable() {
@Override
public void run() {
loadingIndicator.setVisibility((toShow ? View.VISIBLE : View.INVISIBLE));
}
});
}
您可以对 TextView.setText()
这篇关于如何刷新或更新片段UI的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!