Now there is such a simple Fragment:
public class Level1Fragment extends Fragment {
TextView tv;
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
ViewGroup v=inflater.inflate(R.layout.activity_test,null);
tv= (TextView) v.findViewById(R.id.level1_textview);
tv.setText("啦啦啦");
return v;
}
//给View截图,代码应该没有问题
public static Bitmap convertViewToBitmap(View view){
view.measure(View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED), View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED));
view.layout(0, 0, view.getMeasuredWidth(), view.getMeasuredHeight());
view.buildDrawingCache();
return view.getDrawingCache();
}
Now, I want to get a screenshot of this TextView when the Fragment has just been loaded. In which event should I put the code?
I've tried tv.postDelayed()
, tv.post()
and tv.getViewTreeObserver().addOnPreDrawListener()
.
Please also post the code you tried:
@Override
public void onResume() {
super.onResume();
tv.postDelayed(new Runnable() {
@Override
public void run() {
final Bitmap bit=convertViewToBitmap(tv);
//iv只是个简单的ImageView,与本问题无关
iv.setImageBitmap(bit);
iv.startAnimation(new AlphaAnimation(1,0));
}
},100);
}
But they cannot be obtained.
So, what method should be used to correctly obtain the screenshot of tv
?
(btw, Fragment is displayed directly through FragmentTransaction.replace()
, not through ViewPager
, so the life cycle should not be disrupted..)
Solve your doubts!
The first two of the three methods you mentioned are OK, but there is a problem with the last one, which should be
getViewTreeObserver().addOnGlobalLayoutListener()