Stefan Stefan - 3 months ago 14
Android Question

Reference findViewbyID from Fragment in Non-Fragment class

I have a Fragment class

EchossStampFragment
in which I can directly reference


.findViewbyId(R.id.mainView)


In my second non-fragment class
EchossMainView
I want to address this View and change its background.

How can I address it in onInitSuccess like so:

public void onInitSuccess() {
// EchossStampActivity.setText("onInitSuccess");
mainView.setBackgroundColor(Color.RED);
}


in the
EchossMainView
class?

EchossStampFragment Class

public class EchossStampFragment extends Fragment implements EchossStampInterface {
private static final String TAG = MainActivity.class.getSimpleName();
View myView;
private SupportMapFragment mapFragment;
EchossMainView mainView = null;
static TextView textView = null;

@Nullable
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
myView = inflater.inflate(R.layout.activity_echoss, container, false);
return myView;
}

@Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
mainView = (EchossMainView) getView().findViewById(R.id.mainView);
textView = (TextView) getView().findViewById(R.id.textView);
FragmentManager fm = getChildFragmentManager();

// Display Initialization

DisplayMetrics metric = new DisplayMetrics();
getActivity().getWindowManager().getDefaultDisplay().getMetrics(metric);
mainView.init(metric);

mainView.initEchossMainView(this); // this is where we are passing the current activity as interface

// Library Initialization for Stamp
mainView.echossPlatformInit(APIKEY, REGION, LANGUAGE, INDEX);

}


EchossMainView Class

public class EchossMainView extends StampBaseView {

private EchossStampInterface mEchossStampInterface;

public EchossMainView(Context context) {
super(context);
}

public EchossMainView(Context context, AttributeSet attrs) {
super(context, attrs);
}

public EchossMainView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
}

public void onInitSuccess() {
EchossStampActivity.setText("onInitSuccess");
mainView.setBackgroundColor(Color.RED);

}
public void onInitError(String code, String message) {
EchossStampFragment.setText("onInitError - " + code + " " + message);

}


public void onStampSuccess(String stampResult) {
EchossStampFragment.setText("onStampSuccess - " + stampResult);

}

public void onStampError(String code, String message) {
EchossStampFragment.setText("onStampError - " + code + " " + message);
}
}

Answer

Since EchossMainView must eventually extend from View, you can call setBackground from within that class itself:

public void onInitSuccess() {
    setBackgroundColor(Color.RED);
}

Docs for method here: https://developer.android.com/reference/android/view/View.html#setBackgroundColor(int)