[英]Changing an image when button click from another fragment
我希望能夠單擊設置片段上的按鈕,這將更改另一個稱為主片段的片段上的圖像。 單擊按鈕后,我的應用程序不斷崩潰,我不知道為什么。
設置片段:
public class SettingsFragment extends Fragment {
public Button button;
public ImageView Torso;
public ImageView ShopGreenTorso;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
button = (Button) getView().findViewById(R.id.button1);
Torso = (ImageView) getView().findViewById(R.id.Torso);
ShopGreenTorso= (ImageView) getView().findViewById(R.id.ShopGreenTorso);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Toast.makeText(getActivity(), "Purchased", Toast.LENGTH_SHORT).show();
Intent i = new Intent(SettingsFragment.this.getActivity(), AvatarFragment.class);
//i.putExtra("resID", R.drawable.torso2green);
Bundle b= new Bundle();
b.putInt("resID", R.drawable.torso2green);
SettingsFragment.this.setArguments(b);
//setArguments(bundle);
startActivity(i);
}
});
}
頭像片段:
public class AvatarFragment extends Fragment {
public ImageView IV;
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState)
{
View rootView = inflater.inflate(R.layout.fragment_avatar, container, false);
// init image view
IV = (ImageView) rootView.findViewById( R.id.Torso );
// getting extras
//Bundle bundle = getActivity().getIntent().getExtras();
// Bundle bundle=getArguments();
Bundle b=getArguments();
if(b!= null)
{
int resid = b.getInt("resID");
IV.setBackgroundResource(resid);
}
return rootView;
}
}
我相信錯誤來自 IV.setImageResource(resid) 但我不完全確定,任何幫助將不勝感激。
沒有看到異常很難判斷,但這可能是因為 Bundle 映射區分大小寫。
您的SettingsFragment
使用“ResId”,但您的HomeFragment
需要“resID”。 如果在 Bundle 中沒有找到映射,您將獲得resID
的默認值 0。 調用IV.setImageResource(0);
.
您在代碼中的圖像實現是錯誤的,您需要像這樣初始化圖像視圖:
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState)
{
View rootView = inflater.inflate(R.layout.fragment_avatar, container, false);
// init image view
IV = (ImageView) rootView.findViewById( R.id.Torso );
// getting extras
Bundle bundle = getActivity().getIntent().getExtras();
if(bundle!= null)
{
int resid = bundle.getInt("resId");
IV.setImageResource(resid);
}
return rootView;
}
不要將值從 Fragment 直接傳遞到 Fragment。
您應該使用 SettingsFragment 中的setArguments
和getArguments
中的 getArguments
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.