Android适配器父宽度= 0



也许我很累,但是我想念代码中发生的事情。我有一个碎片的活动。

我的活动家庭反应性致电Web服务以填写列表(我的业务对象(,它可以执行此操作((。

我的片段钱包fragment具有使用适配器显示列表的mehtod RefreshcardListView((。它执行此onResume((。

我在做什么,到目前为止一直在工作:

  • homeactitivity.oncreate((显示钱包,walletfragment.onresume((调用this.refreshcardlist((,但在此为即时心列列为null,因此适配器没有显示
  • homeactitivity.onresume((调用WebService,它在成功的电话中alletfragment.refreshcardlist((,这次的卡片列表已填写通过Web服务,因此TID正确显示了列表。

现在我很愚蠢地致电刷新清单两次,所以我试图将DisplayWalletFragment从homeactivity.oncreate((转移到WebService的成功回调,并删除从寄宿家庭中恢复呼叫的呼叫,并仅在Walletfragment.resume.onresume.sonresume.sonresume.sonresume.sonresume.sonresume((,所以它会像这样:

  • homeactivity.onresume((呼叫Web服务,在成功时显示WhatetFragment,WalletFragment.Onresume((call this.refreshcardlist((,CardList已由WebService填写。

但是,在这一点上,我的适配器崩溃了,因为parent.getWidth((== 0(我需要父级宽度以显示卡片图像(。

我不深入了解为什么,通过移动这一点代码,现在的父视会将在此时初始化,您有一个想法吗?

因此,这是我使用的原始代码,我更改的唯一内容是从ongreate中删除displaywalletfragment(false(,并在Refrreshcardlist的成功返回中移动它并删除WalletFragment.RefreshcardListView(从那里(。

homeactivity.java

public class HomeActivity extends Activity {
    CardService cardService = new CardService(this);
    UserService userService = new UserService(this);
    User user = null;
    Set<WegaCard> userCards = null;
    ProfileFragment profileFragment;
    WalletFragment walletFragment;
    /*
     * Saving card images for performance concerns.
     */
    Map<String, Bitmap> cardsImageBitmaps = new HashMap<>();
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_home);
        initializeComponents();
        styleCompnents();
        displayWalletFragment(false);
    }
    @Override
    protected void onResume() {
        Log.d(this, "fired HomeActivity.onResume()");
        super.onResume();
        user = null;
        userCards = null;
        refreshUser(
                new SingleResultCallback<User>() {
                    @Override
                    public void onResponse(User cards) {
                        Log.d(this, "user: " + user.toString());
                        HomeActivity.this.user = user;
                        profileFragment.refreshUser();
                    }
                },
                new ErrorCallback() {
                    @Override
                    public void onResponse(Throwable error) {
                        Log.e(this, "error: " + error.toString());
                    }
                });
        refreshCardList(
                new SingleResultCallback<Set<WegaCard>>() {
                    @Override
                    public void onResponse(Set<WegaCard> cards) {
                        Log.d(this, "cards: " + cards.toString());
                        userCards = cards;
                        walletFragment.refreshCardListView();
                    }
                },
                new ErrorCallback() {
                    @Override
                    public void onResponse(Throwable error) {
                        Log.e(this, "error: " + error.toString());
                    }
                });
    }
    private void refreshCardList(SingleResultCallback<Set<WegaCard>> successCallback, ErrorCallback errorCallback) {
        Log.d(this, "fired HomeActivity.refreshCardList()");
        // First empty list...
        userCards = new LinkedHashSet<>();
        // ...then fill it back
        cardService.getCards(false, true, successCallback, errorCallback);
    }
    private void refreshUser(SingleResultCallback<User> successCallback, ErrorCallback errorCallback) {
        Log.d(this, "fired HomeActivity.refreshUser()");
        // First empty user...
        userCards = new LinkedHashSet<>();
        // ...then recreate it
        userService.getUser(successCallback, errorCallback);
    }
    public void displayWalletFragment(boolean addToBackStack) {
        displayFragment(WalletFragment.newInstance(), addToBackStack);
    }
    public void displayCardFragment(String cardNumber, boolean addToBackStack) {
        displayFragment(CardFragment.newInstance(cardNumber), addToBackStack);
    }
    public void displayProfileFragment(boolean addToBackStack) {
        displayFragment(ProfileFragment.newInstance(), addToBackStack);
    }
    private void displayFragment(HomeFragment fragment, boolean addToBackStack) {
        FragmentManager fragmentManager = getFragmentManager();
        FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
        fragmentTransaction.replace(R.id.home_fragment, fragment);
        if (addToBackStack) {
            fragmentTransaction.addToBackStack(null);
        }
        fragmentTransaction.commit();
    }
    public void profileEdit(View view) {
        ActivityLauncher.getInstance().startProfileActivityForResult(this, ProfileActivity.ProfileEditMode.EDIT_PROFILE, user);
    }
    public Map<String, Bitmap> getCardsImageBitmaps() {
        return cardsImageBitmaps;
    }
}

alletfragment.java

public class WalletFragment extends HomeFragment {
    List<WegaCard> cardList;
    ListView cardListView;
    WegaCardAdapter adapter;
    public static WalletFragment newInstance() {
        WalletFragment fragment = new WalletFragment();
        // Bundle args = new Bundle();
        // fragment.setArguments(args);
        return fragment;
    }
    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        activity.walletFragment = this;
        cardListView = (ListView) getView().findViewById(R.id.fragment_home_wallet_list);
        cardListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                activity.displayCardFragment(cardList.get(position).getCardNumber(), true);
            }
        });
    }
    @Override
    public void onResume() {
        Log.d(this, "fired WalletFragment.onResume()");
        super.onResume();
        refreshCardListView();
    }
    void refreshCardListView() {
        Log.d(this, "fired WalletFragment.refreshCardListView()");
        // First empty list...
        cardList = new ArrayList<>();
        cardList.addAll(activity.userCards);
        adapter = new WegaCardAdapter(activity, R.layout.adapter_card_item, cardList);
        cardListView.setAdapter(adapter);
        getView().findViewById(R.id.fragment_home_wallet_empty).setVisibility(cardList.isEmpty() ? View.VISIBLE : View.GONE);
    }
}

wegacardadapter.java

public class WegaCardAdapter extends ArrayAdapter<WegaCard> {
    public WegaCardAdapter(@NonNull Context context, @LayoutRes int resource, @NonNull List<WegaCard> objects) {
        super(context, resource, objects);
    }
    /**
     * Data that should appear in the view should be added here
     */
    private class ViewHolder {
        ImageView imageView;
    }
    /*
     * Note: using layout_height="match_parent" on the ListView helps Android calculate faster
     * the elements that are displayed on screen, and prevent the array adapter for calling
     * getView() too many times, thus improving the display speed
     */
    public View getView(int position, View convertView, ViewGroup parent) {
        Log.d(this, "fired WegaCardAdapter.getView(" + position + ")");
        ViewHolder holder = null;
        WegaCard card = getItem(position);
        LayoutInflater mInflater = (LayoutInflater) getContext().getSystemService(android.app.Activity.LAYOUT_INFLATER_SERVICE);
        if (convertView == null) {
            convertView = mInflater.inflate(R.layout.adapter_card_item, null);
            holder = new ViewHolder();
            holder.imageView = (ImageView) convertView.findViewById(R.id.adapter_card_image);
            convertView.setTag(holder);
        }
        else {
            holder = (ViewHolder) convertView.getTag();
        }
        Bitmap cardImage = null;
        if (getContext() instanceof HomeActivity) {
            Log.d(this, "In home activity \o/");
            Map<String, Bitmap> savedBitmaps = ((HomeActivity) getContext()).getCardsImageBitmaps();
            if (savedBitmaps.containsKey(card.getCardNumber())) {
                Log.d(this, "Found saved image, using it ^^");
                cardImage = savedBitmaps.get(card.getCardNumber());
            }
            else {
                Log.d(this, "Didn't found saved image éè building and saving it for later!");
                cardImage = card.getRoundedScaledBitmap(getContext(), parent.getWidth());
                savedBitmaps.put(card.getCardNumber(), cardImage);
            }
        }
        else {
            Log.d(this, "Not in home activity?");
            cardImage = card.getRoundedScaledBitmap(getContext(), parent.getWidth());
        }
        holder.imageView.setImageBitmap(cardImage);
        return convertView;
    }
}

activity_home.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:auto="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent">
    <ScrollView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:fillViewport="true">
        <!-- Fragment will be displayed here -->
        <LinearLayout
            android:id="@+id/home_fragment"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:orientation="vertical">
        </LinearLayout>
    </ScrollView>
</RelativeLayout>

fragment_home_wallet.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">
    <LinearLayout
        android:id="@+id/fragment_home_wallet_root"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical"
        android:gravity="center">
        <LinearLayout
            android:id="@+id/fragment_home_wallet_empty"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:orientation="vertical"
            android:gravity="center"
            android:visibility="gone">
            <ImageView
                android:src="@drawable/icon_card_white"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content" />
            <com.gaetanl.aspa.ui.component.StaticTextView
                android:id="@+id/fragment_home_wallet_empty_title"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_marginTop="@dimen/defaultSpacing"
                android:text="@string/dashboard_text_nocard" />
            <LinearLayout
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_marginTop="@dimen/defaultSpacing"
                android:gravity="center_vertical"
                android:orientation="horizontal">
                <com.gaetanl.aspa.ui.component.StaticTextView
                    android:id="@+id/fragment_home_wallet_empty_text1"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:text="@string/dashboard_text_tap1" />
                <ImageView
                    android:src="@drawable/icon_plus_white"
                    android:layout_width="@dimen/inlineIcon"
                    android:layout_height="@dimen/inlineIcon"
                    android:layout_marginLeft="@dimen/wordSpacing"
                    android:layout_marginRight="@dimen/wordSpacing" />
                <com.gaetanl.aspa.ui.component.StaticTextView
                    android:id="@+id/fragment_home_wallet_empty_text2"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:text="@string/dashboard_text_tap2" />
            </LinearLayout>
        </LinearLayout>
        <!-- Note: using layout_height="match_parent" on the ListView helps Android calculate faster
         the elements that are displayed on screen, and prevent the array adapter for calling
         getView() too many times, thus improving the display speed -->
        <ListView
            android:id="@+id/fragment_home_wallet_list"
            android:layout_width="match_parent"
            android:layout_height="match_parent">
        </ListView>
    </LinearLayout>
</LinearLayout>

我在这里找到了解决方案:何时应该在片段中获得宽度视图。

@Override
public void onViewCreated(View view, Bundle savedInstanceState) {
    super.onViewCreated(view, savedInstanceState);
    view.post(new Runnable() {
        @Override
        public void run() {
            // do operations or methods involved
            // View.getWidth(); or View.getHeight();
            // here
        }
    });
}

您可以尝试在成功回调上只调用displayWalletFragment(false);,然后将walletFragment.refreshCardListView();移至WallentFragmentonViewCreated()

这将确保创建Fragment的正确顺序和被填充的列表。

最新更新