我们从onCreate方法获取someID的值。当onCreateView方法第一次运行时,一切都很好。但是,在第二次运行(1000间隔后),someID值为NULL。我们如何确保这个someID值是粘性的?请记住,此线程存在于片段
中@Override
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
someID = getArguments().getString(SOME_ID_KEY);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState){
View v = inflater.inflate(R.layout.fragment_game, container, false);
Toast.makeText(getActivity(), someID, Toast.LENGTH_SHORT).show();
handler.postDelayed(new Runnable() {
@Override
public void run() {
System.out.print(someID); // works on 1st time but not any other future runs of the 1k interval
handler.postDelayed(this, 1000);
}
}, 1000);
答案 0 :(得分:1)
你可以这样做
private void printId(){
handler.postDelayed(new Runnable() {
@Override
public void run() {
System.out.print(someID); // works on 1st time but not any other future runs of the 1k interval
printId();
}
}, 1000);
}
并在onCreateView中将所有处理程序代码替换为:
pirntId();