0

В приложении с DrawerLayout при нажатии на кнопку "add account" в заголовке левого Drawer я показываю ListFragment со списком из шести соц. сетей:

screenshot

Сперва ListFragment выглядит (почти) как нужно - но при повороте почему-то исчезает (или очищается?) список соц. сетей и я видимо не понимаю какой-то простой вещи, почему это происходит и как решить эту проблему.

Вот код в MainActivity.java обрабатывающий нажатие на "add account":

public void showAccounts(View v) {
    mDrawerLayout.closeDrawer(mLeftDrawer);

    final AccountFragment fragment = new AccountFragment();
    fragment.setListAdapter(new ArrayAdapter<String>(this,
            android.R.layout.simple_list_item_1,
            Utils.ACCOUNT_LABELS) {
        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            TextView view = (TextView) super.getView(position, convertView, parent);
            view.setCompoundDrawablePadding(24);
            view.setCompoundDrawablesWithIntrinsicBounds(Utils.ACCOUNT_ICONS[position], 0, 0, 0);
            return view;
        }
    });

    mHandler.postDelayed(new Runnable() {
        @Override
        public void run() {
            getSupportFragmentManager().beginTransaction()
                    .addToBackStack(null)
                    .replace(R.id.root, fragment, Utils.ACCOUNTS)
                    .commit();
        }
    }, DRAWER_CLOSE_DELAY_MS);
}

Вот показваемый потом AccountFragment.java:

public class AccountFragment extends ListFragment {
    public AccountFragment() {
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment_account, container, false);
    }

    @Override
    public void onListItemClick(ListView l, View v, int position, long id) {
        Toast.makeToast(getContext(), "You have clicked " + Utils.ACCOUNT_LABELS[position], Toast.LENGTH_SHORT).show();
    }
}

И соответствующий fragment_account.xml (с парой дополнительных проблем):

<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <de.hdodenhof.circleimageview.CircleImageView
        android:id="@+id/avatar"
        android:layout_width="96dp"
        android:layout_height="96dp"
        android:layout_gravity="center_horizontal"
        android:src="@drawable/photo"
        app:border_width="2dp"
        app:border_color="#FFF"/>

    <TextView
        android:id="@+id/username"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:textAppearance="@style/TextAppearance.AppCompat.Body1"
        android:layout_gravity="center_horizontal"
        android:text="Username"
        />                      <!-- почему-то не в центре -->

    <ListView
        android:id="@android:id/list"
        android:layout_width="match_parent"
        android:layout_height="match_parent" >
    </ListView>                 <!-- не уверен насчет высоты -->

</LinearLayout>

В отладчике видно, что при повороте телефона вызывается заново onCreateView() - но почему это очищает или прячет ListView?

ОБНОВЛЕНИЕ: Я передвинул вызов setListAdapter() в onAttach() - как было предложено Eugene Krivenja (спасибо!) в тестовом проекте на GitHub и теперь список не исчезает при повороте телефона.

Осталась только косметическая проблема с двумя TextViews из fragment_account.xml не в середине экрана (помечены красной стрелкой):

screenshot

2
  • 1
    По тексту по центру - думаю в атрибутах TextView вместо параметров android:textAlignment="center" или android:layout_gravity="center_horizontal" нужно установить гравити внутри виджета, а не выравнивание текста или гравити относительно родительского лэйаута: android:gravity="center_horizontal" - должно решить вашу проблему
    – pavlofff
    24 авг 2015 в 16:38
  • android:gravity="center_horizontal" и android:layout_width="wrap_content" помогло! 24 авг 2015 в 17:12

1 ответ 1

1

Потому что фрагмент персоздается системой с помощью конструктора без параметров. И все. Соответственно, этот код

fragment.setListAdapter(new ArrayAdapter<String>(this,
        android.R.layout.simple_list_item_1,
        Utils.ACCOUNT_LABELS) {
    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        TextView view = (TextView) super.getView(position, convertView, parent);
        view.setCompoundDrawablePadding(24);
        view.setCompoundDrawablesWithIntrinsicBounds(Utils.ACCOUNT_ICONS[position], 0, 0, 0);
        return view;
    }
});

не выполняется.

Перенесите его в AccountFragment.onAttach() и все будет Ок.

0

Ваш ответ

By clicking “Отправить ответ”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.