简书链接:fragment的findbyid代码写在哪里比较合适?
文章字数:89,阅读全文大约需要1分钟

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
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的时候还是需要考虑的。