trakasi trakasi - 3 days ago 5
Android Question

Android Studio "Refresh" fragment(s) layout from MainActivity

It's been a while, when I am trying to figure out my problem.

I want to "refresh" my fragments layout widgets, for example, textviews, imageviews, cardviews, and all other.

I'm trying to do this like:

((ImageView) findViewById(R.id.BCFrame)).setImageResource(R.drawable.frame_1_6);



But, it always shows, nullObjectPointer error(Becouse these for
example CardViews are in other layout.)


I have figured out, that I can refresh them, when I click somewhere in that fragment, with "onClick" function

public void RefreshUpgrade(View view){
((TextView) findViewById(R.id.PlayerUpgradeTView)).setText("Player level: " +Main.PlayerLevel[0]);
((TextView) findViewById(R.id.BoxUpgradeTView)).setText("Box level: " + Main.BoxesLevel[0]);
((TextView) findViewById(R.id.GarageUpgradeTView)).setText("Garage level: " + Main.GarageLevel[0]);
((TextView) findViewById(R.id.GarageSlotsTView)).setText("Garage slots: " + Main.GarageSlots[0]);
((TextView) findViewById(R.id.short_description222)).setText("Money: " + Main.Money[0] + "/600");
((TextView) findViewById(R.id.short_description22)).setText("Boxes Opened: " + Main.BoxesOpened[0] + "/30");

if(Main.Money[0] >= 600){
((TextView) findViewById(R.id.short_description222)).setTextColor(0xff00ff00);
}
}


But I need 2 things, that can't figure out.

1.I need these objects to "refresh" automatically, if arguments are true(if statements in MainActivity)

2.I need these objects to "refresh" automatically, after some time have went(Like GameLoop).

In Simple Java I got this all working, but there I got only JPanels, nothing like fragments.

Answer

Don't search for the Views in your Activity that belong to the Fragment. In your Fragment class store them in varibles like e.g.

class Fragment
private TextView playerUpgradeTextView;

 public void refreshViews(){
 // your refreshUpgrade() method
}

 @Override
 public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View v = inflater.inflate(R.layout.yourFragmentLayout, container, false);
        playerUpgradeTextView = (TextView) v.findViewById(R.id.PlayerUpgradeTView)
        return v;
    }

Since your Activity holds your Fragment you can call the refreshViews method and pass it method parameters if needed.

Your second question is more a classic periodic event which also calls the refreshViews method.

Comments