在非片段类

时间:2016-08-29 20:28:29

标签: android android-fragments findviewbyid

我有一个Fragment类EchossStampFragment,我可以在其中直接引用

  

.findViewbyId(R.id.mainView)

在我的第二个非片段类EchossMainView中,我想解决此视图并更改其背景。

我如何在onInitSuccess中解决它,如下所示:

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

EchossMainView班?

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类

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);
    }
}

1 个答案:

答案 0 :(得分:2)

由于EchossMainView最终必须从View扩展,因此您可以从该类本身调用setBackground:

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

此方法的文档:https://developer.android.com/reference/android/view/View.html#setBackgroundColor(int)