fragment的findbyid代码写在哪里比较合适?

public class DFPFluidSizeFragment extends Fragment {

    private PublisherAdView publisherAdView;
    private Button changeAdViewWidthButton;
    private TextView currentWidthTextView;
    private final int[] adViewWidths = new int[]{200, 250, 320};
    private int currentIndex = 0;

    public DFPFluidSizeFragment() {
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        return inflater.inflate(R.layout.fragment_dfp_fluid_size, container, false);
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);

        // The size for this PublisherAdView is defined in the XML layout as AdSize.FLUID. It could
        // also be set here by calling publisherAdView.setAdSizes(AdSize.FLUID).
        //
        // An ad with fluid size will automatically stretch or shrink to fit the height of its
        // content, which can help layout designers cut down on excess whitespace.
        publisherAdView = getView().findViewById(R.id.fluid_av_main);

        PublisherAdRequest publisherAdRequest = new PublisherAdRequest.Builder().build();
        publisherAdView.loadAd(publisherAdRequest);

        changeAdViewWidthButton = getView().findViewById(R.id.fluid_btn_change_width);
        changeAdViewWidthButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                int newWidth = adViewWidths[currentIndex % adViewWidths.length];
                currentIndex += 1;
                // Change the PublisherAdView's width.
                ViewGroup.LayoutParams layoutParams = publisherAdView.getLayoutParams();
                final float scale = getResources().getDisplayMetrics().density;
                layoutParams.width = (int) (newWidth * scale + 0.5f);
                publisherAdView.setLayoutParams(layoutParams);
                // Update the TextView with the new width.
                currentWidthTextView = getView().findViewById(R.id.fluid_tv_current_width);
                currentWidthTextView.setText(
                        String.format(Locale.getDefault(), "%d dp", newWidth));
            }
        });
    }
}

这是官方的demo,onActivityCreated调用的时候就可以写了。通常情况下我的习惯是在onViewCreated的时候就写了,那个时候findbyid当然是可以正常执行的。但是activity还没创建呢,要用activity的时候还是需要考虑的。

你可能感兴趣的:(fragment的findbyid代码写在哪里比较合适?)