我創建了一個標籤活動,名爲UserProfile.java
。正如你們許多人所知道的那樣,這種活動帶有一個名爲PlaceholderFragment
的內置類,它基本上是魔法發生的地方。礦山看起來如下:從PlaceHolderFragment執行AsyncTask:「'com.example.Activity.this'無法從靜態上下文中引用」
public static class PlaceholderFragment extends Fragment {
private static final String ARG_SECTION_NUMBER = "section_number";
public PlaceholderFragment() {
}
public static PlaceholderFragment newInstance(int sectionNumber) {
PlaceholderFragment fragment = new PlaceholderFragment();
Bundle args = new Bundle();
args.putInt(ARG_SECTION_NUMBER, sectionNumber);
fragment.setArguments(args);
return fragment;
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Some code related to database queries irrelevant to this question...
if (getArguments().getInt(ARG_SECTION_NUMBER) == 1) {
View profileView = inflater.inflate(
R.layout.fragment_user_profile_data,
container,
false
);
// Here's some code intended to get edittext's values irrelevant to this question...
final Button saveProfile = (Button) profileView.findViewById(R.id.profile_save_data);
saveProfile.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
UpdateProfileForm upf = new UpdateProfileForm(
userName.getText().toString(),
userLastName.getText().toString(),
userID.getText().toString(),
userPhone.getText().toString(),
userEmail.getText().toString(),
userAddress.getText().toString()
);
new UpdateProfile().execute(upf);
view.setVisibility(View.GONE);
}
});
return profileView;
} else if (getArguments().getInt(ARG_SECTION_NUMBER) == 2) {
View profileView = inflater.inflate(R.layout.another_fragment, container, false);
return profileView;
} else {
View profileView = inflater.inflate(R.layout.fragment_user_profile_data, container, false);
return profileView;
}
}
}
正如你所看到的,我有一個表格片段稱爲fragment_user_profile_data
從哪裏獲得用戶的數據,一個UpdateProfileForm
類來存儲它並把它傳遞到的AsyncTask叫UpdateProfile
用於更新用戶信息在服務器端點擊saveProfile
按鈕。
但是,如果嘗試該行
new UpdateProfile().execute(upf);
的
'com.example.UserProfile.this' 不能從靜態上下文
錯誤引用將由Android Studio顯示。我被告知要麼從PlaceholderFragment類中取消「靜態」屬性,要麼讓我的AsyncTask靜態,但它們都不起作用。
我被困在這個,所以任何幫助將不勝感激!
你真的應該使用三個單獨的片段類,而不是讓一個片段根據'ARG_SECTION_NUMBER'處理三個單獨的責任。 –
@ cricket_007請問您可以告訴我更多關於如何完成這個任務嗎?這聽起來像正確的方式(以及我想要的方式)來做,但我見過的唯一選項卡式活動教程使用了此佔位符片段。 –
連接到TabLayout的ViewPager的PagerAdapter根據位置決定要加載哪個片段 –