[英]Android: In the fragment class, on accessing a variable of Activity class through it's getter method, the variable's value remains 0
Activity類在onCreate方法中具有一個整數,該整數通過getIntent設置。
pos = getIntent().getIntExtra("position", -1);
-1是getIntExtra()的默認值,“位置”是將其存儲在另一個類中的關鍵。 對於點擊,此值應該是動態的。 但是,通過活動的getpos()方法在fragment類中訪問它時,它始終返回0。為什么?
這是Acitivity類的OnCreate方法:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_detail);
pos = getIntent().getIntExtra("position", -1);}
這是Acitivity類的pos的getter方法:
public int get(){
return pos;
}
這是Fragment的onCreateView方法:
//an inflater
Activity my=(Activity) getActivity();
int posfrag = my.get();
我正在嘗試通過此方法訪問Recycler View的項目位置,但是雖然pos在Activity方法中已正確更新,但是這里的posfrag並沒有得到更新。 問題在於將保留值傳遞給片段。
嘗試在Fragment的onActivityCreated()方法中獲取pos值。
@Override
public void onActivityCreated(@Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
// retrieve your variable value here
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.