我的Firebase崩溃报告显示以下代码在极少数设备上出现故障。我无法重现这个问题。任何人都可以建议可能是什么问题?看来问题是imageView.getWidth()或imageView.getHeight()返回零。
以下代码在我的片段中:
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_category_list, container, false);
final ImageView imageView = (ImageView) view.findViewById(R.id.categoryBackgrndImageView);
// Set an observer that is called after the imageView is laid out
imageView.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
@Override
public void onGlobalLayout() {
//now we can retrieve the width and height
int width = imageView.getWidth();
int height = imageView.getHeight();
// etc. Code here removed. It gets an asset and creates a bitmap from the
// asset, sizing the bitmap based on the imageView width and height
}
这是布局:
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:menu="menu_main,menu_categories">
<ImageView
android:id="@+id/categoryBackgrndImageView"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:scaleType="centerCrop" />
<technology.grandma.margriver.AutoGridRecylerView
android:id="@+id/categoryRecyclerView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:columnWidth="330dp"
android:scrollbars="vertical"
tools:listitem="@layout/list_item_category"/>
</FrameLayout>
我的互联网研究似乎证实这段代码是正确的。你能在这里看到什么问题吗?
答案 0 :(得分:0)
尝试改用OnLayoutChangeListener
:
imageView.addOnLayoutChangeListener(new View.OnLayoutChangeListener() {
@Override
public void onLayoutChange(View v, int left, int top, int right, int bottom, int oldLeft, int oldTop, int oldRight, int oldBottom) {
int width = imageView.getMeasuredWidth();
int height = imageView.getMeasuredHeight();
imageView.removeOnLayoutChangeListener(this);
}
});
由于OnGlobalLayoutListener
观察了布局更改的所有层次结构,因此,假设在层次结构中放置任何视图时都可以触发该变化。同时,measuredWidth
和measuredHeight
在这个时候更可能是已知的。