Урок 105. Android 3. Fragments. Динамическая работа

Обсуждение уроков
Аватара пользователя
Mikhail_dev
Сообщения: 2386
Зарегистрирован: 09 янв 2012, 14:45
Откуда: Самара

Re: Урок 105. Android 3. Fragments. Динамическая работа

Сообщение Mikhail_dev » 09 сен 2015, 10:43

P.S. почему-то преестала работать конструкция "[syntax = java][ / syntax]" для обозначения кода.
P.P.S. klblk верно указал на еще одни моменты.

K_Vladimir
Сообщения: 36
Зарегистрирован: 28 июн 2015, 03:13

Re: Урок 105. Android 3. Fragments. Динамическая работа

Сообщение K_Vladimir » 09 сен 2015, 11:02

Спасибо!!!
Как будет время сразу же все это проверю и напишу.

K_Vladimir
Сообщения: 36
Зарегистрирован: 28 июн 2015, 03:13

Re: Урок 105. Android 3. Fragments. Динамическая работа

Сообщение K_Vladimir » 13 сен 2015, 21:04

Доброго дня!
Спасибо klblk и Mikhail_dev за помощь! Все замечания оказались крайне полезными и правильными.
Думаю, что все это хорошо бы подправить в самом уроке. Чтобы люди сразу делали правильно, а не накапливали груз ошибок.
Выкладываю свою последнюю работающую версию по уроку с проверкой нескольких действий в одной транзакции.

MainActivity

Код: Выделить всё

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v4.app.FragmentTransaction;
import android.view.View;
import android.widget.CheckBox;

public class MainActivity extends AppCompatActivity {

    static final String TAG_FRAGMENT1 = "Teg_Fragment1";
    static final String TAG_FRAGMENT2 = "Teg_Fragment2";
    static final String TAG_FRAGMENT3 = "Teg_Fragment3";
    static final String TAG_FRAGMENT4 = "Teg_Fragment4";

    Fragment1 frag1;
    Fragment2 frag2;
    Fragment3 frag3;
    Fragment4 frag4;
  //  FragmentTransaction fTrans;
    CheckBox chbStack;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

     //   frag1 = new Fragment1();
     //   frag2 = new Fragment2();

        chbStack = (CheckBox)findViewById(R.id.chbStack);
    }

    public void onClick(View v) {
        FragmentTransaction fTrans;
        fTrans = getSupportFragmentManager().beginTransaction();
        switch (v.getId()) {
            case R.id.btnAdd:
                frag1 = (Fragment1) getSupportFragmentManager().findFragmentByTag(TAG_FRAGMENT1);
                if (frag1 == null) frag1 = new Fragment1();
                fTrans.add(R.id.frgmCont, frag1, TAG_FRAGMENT1);
                frag3 = (Fragment3) getSupportFragmentManager().findFragmentByTag(TAG_FRAGMENT3);
                if (frag3 == null) frag3 = new Fragment3();
                fTrans.add(R.id.frgmCont, frag3, TAG_FRAGMENT3);
                break;
            case R.id.btnRemove:
                frag1 = (Fragment1) getSupportFragmentManager().findFragmentByTag(TAG_FRAGMENT1);
                if (frag1 != null) fTrans.remove(frag1);
                break;
            case R.id.btnReplace:
                frag2 = (Fragment2) getSupportFragmentManager().findFragmentByTag(TAG_FRAGMENT2);
                if (frag2 == null) frag2 = new Fragment2();
                fTrans.replace(R.id.frgmCont, frag2, TAG_FRAGMENT2);
                frag4 = (Fragment4) getSupportFragmentManager().findFragmentByTag(TAG_FRAGMENT4);
                if (frag4 == null) frag4 = new Fragment4();
                fTrans.replace(R.id.frgmCont, frag4, TAG_FRAGMENT2);
            default:
                break;
        }

        if (chbStack.isChecked()) fTrans.addToBackStack(null);
        fTrans.commit();
    }
}
Один из 4-х фрагментов (Добавил логи, чтоб посмотреть что с фрагментами происходит)

Код: Выделить всё

import android.content.Context;
import android.support.v4.app.Fragment;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

public class Fragment1 extends Fragment {

    final String LOG_TAG = "myLogs";

    public void onAttach(Context context) {
        super.onAttach(context);
        Log.d(LOG_TAG, "Fragment1 onAttach");
    }

    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Log.d(LOG_TAG, "Fragment1 onCreate");
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
     //   return inflater.inflate(R.layout.fragment1, null);
        Log.d(LOG_TAG, "Fragment1 onCreateView");
        return  inflater.inflate(R.layout.fragment1, container, false);
    }

    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        Log.d(LOG_TAG, "Fragment1 onActivityCreated");
    }

    public void onStart() {
        super.onStart();
        Log.d(LOG_TAG, "Fragment1 onStart");
    }

    public void onResume() {
        super.onResume();
        Log.d(LOG_TAG, "Fragment1 onResume");
    }

    public void onPause() {
        super.onPause();
        Log.d(LOG_TAG, "Fragment1 onPause");
    }

    public void onStop() {
        super.onStop();
        Log.d(LOG_TAG, "Fragment1 onStop");
    }

    public void onDestroyView() {
        super.onDestroyView();
        Log.d(LOG_TAG, "Fragment1 onDestroyView");
    }

    public void onDestroy() {
        super.onDestroy();
        Log.d(LOG_TAG, "Fragment1 onDestroy");
    }

    public void onDetach() {
        super.onDetach();
        Log.d(LOG_TAG, "Fragment1 onDetach");
    }

}
main.xml

Код: Выделить всё

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/LinearLayout1"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">
    <LinearLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:orientation="vertical">
        <Button
            android:id="@+id/btnAdd"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:onClick="onClick"
            android:text="@string/add">
        </Button>
        <Button
            android:id="@+id/btnRemove"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:onClick="onClick"
            android:text="@string/remove">
        </Button>
        <Button
            android:id="@+id/btnReplace"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:onClick="onClick"
            android:text="@string/replace">
        </Button>
        <CheckBox
            android:id="@+id/chbStack"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="@string/stack">
        </CheckBox>
    </LinearLayout>
    <LinearLayout
        android:id="@+id/frgmCont"
        android:orientation="vertical"
        android:layout_width="match_parent"
        android:layout_height="match_parent">
    </LinearLayout>
</LinearLayout>
fragment1.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"
    android:background="#77ff0000"
    android:layout_weight="1">
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/frag1_text">
    </TextView>
</LinearLayout>

danek130995
Сообщения: 42
Зарегистрирован: 25 янв 2015, 18:57

Re: Урок 105. Android 3. Fragments. Динамическая работа

Сообщение danek130995 » 14 окт 2015, 16:56

Neustart писал(а):ОБРАЩАЮСЬ К АВТОРУ УРОКА !
Я промучился над уроком три часа. Все дело в том, что addToBackStack() нифига не работает. нажатие кнопки "Назад", выходит из приложения. Что я только не делал. Сидел изучал логи, отлавливал экспешены, все впустую.
Все дело оказалось в том, что в первых уроках, вы научили создавать в Android Studio - MainActivity. Соответственно я все время пока изучаю эти уроки так и делаю. Но уроки писались то в эклипсе, и там активи по умолчанию - Activity. Оказалось, что если наследовать MainActivity от Activity то все работает как надо. НО по умолчанию оно то наследует от ActionBarActivity !!!!!!!!!
Внесите хоть какую-то информацию об этом в урок. Я думаю я не один такой промучился пару часов над поиском решения.
Спасибо.
Спасибо Вам, помогло.

maldalik
Сообщения: 3
Зарегистрирован: 04 апр 2016, 10:24

Re: Урок 105. Android 3. Fragments. Динамическая работа

Сообщение maldalik » 04 апр 2016, 10:32

У меня возникла следующая проблема, у меня есть header и footer layouts, между ними frame с заменой фрагментов. Но высоту фрагмента не смог отрегулировать от слова совсем, он все равно поджимает footer, что бы я не писал в параметр layout_height, wrap_content, match_parent или фиксированный размер. То же пытался сделать и в фрагментах, без эффекта. Куда копать?
Что б было понятно о чем речь прилагаю скрин(фон убрал что бы видан была граница лайоута), белая полоса внизу должна быть сильно меньше по идее как ее уменьшить?

Код: Выделить всё

 <?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical" android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:id="@+id/lbody">

    <RelativeLayout
        android:orientation="vertical"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/lTop"
        android:background="@color/НТС"
        >

        <ImageView
            android:src="@drawable/logonts"
            android:layout_width="200dp"
            android:layout_height="250dp"
            android:id="@+id/imLogo"
            android:scaleType="fitStart"
            android:layout_alignParentTop="true"
            android:layout_alignParentLeft="true"
            android:visibility="visible" />

        <TextView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:textAppearance="?android:attr/textAppearanceLarge"
            android:text="Иванов Иван Иванович"
            android:id="@+id/txtFIO"
            android:textSize="25sp"
            android:layout_marginLeft="50dp"
            android:layout_marginTop="130dp"
            android:layout_centerHorizontal="true"
            android:layout_marginBottom="15dp" />

        <TextView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:textAppearance="?android:attr/textAppearanceLarge"
            android:textSize="25sp"
            android:text="CATV"
            android:id="@+id/txtContract"
            android:layout_below="@id/txtFIO"
            android:layout_alignLeft="@id/txtFIO" />

        <TextView
            android:layout_width="130dp"
            android:layout_height="wrap_content"
            android:textAppearance="?android:attr/textAppearanceLarge"
            android:textSize="20sp"
            android:textColor="@color/BlueHTC"
            android:text="Баланс:500Р"
            android:id="@+id/txtbalance"
            android:layout_below="@id/txtContract"
            android:layout_marginTop="15dp"
            android:layout_alignStart="@id/txtContract" />

        <Button
            android:layout_width="wrap_content"
            android:layout_height="30dp"
            android:text="пополнить"
            android:id="@+id/btpays"
            android:textColor="@color/BlueHTC"
            android:textSize="10sp"
            android:layout_alignBottom="@id/txtbalance"
            android:background="@drawable/rounddirectinv"
            android:layout_toRightOf="@id/txtbalance" />

        <Button
            android:layout_width="wrap_content"
            android:layout_height="30dp"
            android:text="напомнить"
            android:id="@+id/btSMS"
            android:textColor="@color/BlueHTC"
            android:textSize="10sp"
            android:background="@drawable/rounddirectinv"
            android:layout_alignBottom="@+id/txtbalance"
            android:layout_marginLeft="10dp"
            android:layout_toRightOf="@id/btpays"
            />
    </RelativeLayout>
    <FrameLayout
        android:id="@+id/frgmCont"
        android:layout_width="match_parent"
        android:layout_below="@id/lTop"
        android:layout_height="wrap_content"
        android:layout_above="@+id/lBottom">
    </FrameLayout>

    <RelativeLayout
        android:orientation="vertical"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/lBottom"
        android:layout_alignParentBottom="true"
        android:background="@color/НТС"
        android:layout_centerHorizontal="true">

        <Button
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="910-910"
            android:drawableLeft="@drawable/telephone"
            android:id="@+id/btCallisc"
            android:layout_marginLeft="50dp"
            android:background="@color/НТС"
             />
        <Button
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Заказать звонок"
            android:id="@+id/btRecall"
            android:textAllCaps="false"
            android:background="@drawable/roundrect"
            android:textColor="@color/WhiteHTC"
            android:layout_alignParentEnd="true"
            android:layout_marginEnd="50dp" />

        <Button
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Задать вопрос"
            android:id="@+id/btQuestion"
            android:background="@drawable/roundrect"
            android:layout_below="@id/btRecall"
            android:textAllCaps="false"
            android:textColor="@color/WhiteHTC"
            android:layout_marginTop="15dp"
            android:layout_marginBottom="15dp"
            android:layout_alignLeft="@id/btRecall"
            android:layout_alignRight="@id/btRecall" />
    </RelativeLayout>


</RelativeLayout>

Код: Выделить всё

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:background="@color/НТС"
    android:layout_height="wrap_content">
    <Button
        android:layout_width="match_parent"
        android:layout_height="50dp"
        android:id="@+id/btdogdata"
        android:layout_marginTop="@dimen/fab_margin"
        android:background="@drawable/standartbluebtn"
        android:textColor="@color/WhiteHTC"
        android:textStyle="bold"
        android:textAllCaps="false"
        android:drawableLeft="@drawable/printer"
        android:text="Данные по договору"
        android:layout_centerHorizontal="true" />

    <Button
        android:layout_width="match_parent"
        android:layout_height="50dp"
        android:id="@+id/btpaysmain"
        android:background="@drawable/standartbluebtn"
        android:textColor="@color/WhiteHTC"
        android:textStyle="bold"
        android:textAllCaps="false"
        android:layout_below="@+id/btdogdata"
        android:drawableLeft="@drawable/ruble"
        android:text="Оплата"
        android:layout_centerHorizontal="true" />

    <Button
        android:layout_width="match_parent"
        android:layout_height="50dp"
        android:id="@+id/HTCClub"
        android:background="@drawable/standartbluebtn"
        android:textColor="@color/WhiteHTC"
        android:textStyle="bold"
        android:textAllCaps="false"
        android:layout_below="@id/btpaysmain"
        android:drawableLeft="@drawable/gift"
        android:text="НТС-Клуб"
        android:layout_centerHorizontal="true" />

    <Button
        android:layout_width="match_parent"
        android:layout_height="50dp"
        android:id="@+id/btNews"
        android:background="@drawable/standartbluebtn"
        android:textColor="@color/WhiteHTC"
        android:textStyle="bold"
        android:textAllCaps="false"
        android:layout_below="@id/HTCClub"
        android:drawableLeft="@drawable/news"
        android:text="Новости"
        android:layout_alignEnd="@+id/HTCClub" />
</LinearLayout>

Код: Выделить всё

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:background="@color/НТС"
    android:layout_height="wrap_content">

    <Button
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:drawableLeft="@drawable/yellowcircle"
        android:text="Напоминание"
        android:textColor="@color/BlueHTC"
        android:textStyle="bold"
        android:background="@drawable/norondtransparentshape"
        android:id="@+id/btncaption" />

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/lbltextfrgm3"
        android:textSize="20sp"
        android:id="@+id/lbltext"
        android:layout_marginLeft="20dp"
        android:layout_marginRight="20dp"
        android:layout_below="@id/btncaption"
        android:layout_marginTop="@dimen/fab_margin"
        android:layout_gravity="center_horizontal" />
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="15dp"
        android:text="Напомнить за:"
        android:layout_below="@id/lbltext"
        android:textSize="20sp"
        android:id="@+id/lbltext2"
        android:layout_marginLeft="20dp"
        android:layout_marginRight="20dp"

         />

    <EditText
        android:layout_width="40dp"
        android:layout_height="wrap_content"
        android:layout_below="@id/lbltext"
        android:layout_marginTop="15dp"
        android:layout_toRightOf="@id/lbltext2"
        android:background="@drawable/conturs"
        android:id="@+id/txtDays" />

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="15dp"
        android:text="дней"
        android:layout_below="@id/lbltext"
        android:textSize="20sp"
        android:id="@+id/lbltext3"
        android:layout_toRightOf="@id/txtDays"
        android:layout_marginLeft="20dp"
        android:layout_marginRight="20dp"
        />
    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="ПРИМЕНИТЬ"
        android:id="@+id/btApplyremember"
        android:layout_marginTop="10dp"
        android:textAllCaps="false"
        android:background="@drawable/roundrect"
        android:textColor="@color/WhiteHTC"
        android:layout_below="@id/txtDays"
        android:layout_centerHorizontal="true" />
</RelativeLayout>
Вложения
fragm1.png
fragm1.png (150.36 КБ) 6014 просмотров

Кошки Рулят
Сообщения: 9
Зарегистрирован: 15 мар 2016, 03:10

Re: Урок 105. Android 3. Fragments. Динамическая работа

Сообщение Кошки Рулят » 04 апр 2016, 17:01

Код: Выделить всё

<Button 
        android:layout_width="match_parent" 
        android:layout_height="50dp" 
        android:id="@+id/btNews" 
        android:background="@drawable/standartbluebtn" 
        android:textColor="@color/WhiteHTC" 
        android:textStyle="bold" 
        android:textAllCaps="false" 
        android:layout_below="@id/HTCClub" 
        android:drawableLeft="@drawable/news" 
        android:text="Новости" 
        android:layout_alignEnd="@+id/HTCClub" 

        android:layout_marginBottom="5dp"

/>
Отступ снизу не поможет?

Код: Выделить всё

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" 
    android:orientation="vertical" 
    android:layout_width="match_parent" 

    android:layout_height="match_parent" 

    android:id="@+id/lbody"> 
Т.е. лайяут в котором у тебя лежат другие лаяуты в которых лежат кнопки и пр. пытается занять по высоте match_parent, вероятно, "растягивая" для этого "средний" лайяут, т.к. сумма высот лаяутов меньше высоты экрана.
Тебе действительно нужна вся высота? Тогда скажи ему какими полями у каких лаяутов ему добавить суммарной высоты

Аватара пользователя
Foenix
Сообщения: 4201
Зарегистрирован: 20 окт 2012, 12:01

Re: Урок 105. Android 3. Fragments. Динамическая работа

Сообщение Foenix » 04 апр 2016, 17:21

даже не стоит делать такую реализацию такого плохого дизайна

https://www.google.com/design/spec/mate ... ction.html

https://www.google.com/design/spec/layo ... aper-works
R.id.team

NullPointerException - что делать???
viewtopic.php?f=33&t=3899&p=28952#p28952
Где моя ошибка?
viewtopic.php?f=60&t=3198

maldalik
Сообщения: 3
Зарегистрирован: 04 апр 2016, 10:24

Re: Урок 105. Android 3. Fragments. Динамическая работа

Сообщение maldalik » 06 апр 2016, 04:53

Так в том то и беда что он поджимает нижний layout, который съеживается, у верхней кнопки пропал отступ сверху.
То есть на самом деле ничего растягивать не надо. в итоге решил проблему фиксацией высоты нижнего layout
Кошки Рулят писал(а):

Код: Выделить всё

<Button 
        android:layout_width="match_parent" 
        android:layout_height="50dp" 
        android:id="@+id/btNews" 
        android:background="@drawable/standartbluebtn" 
        android:textColor="@color/WhiteHTC" 
        android:textStyle="bold" 
        android:textAllCaps="false" 
        android:layout_below="@id/HTCClub" 
        android:drawableLeft="@drawable/news" 
        android:text="Новости" 
        android:layout_alignEnd="@+id/HTCClub" 

        android:layout_marginBottom="5dp"

/>
Отступ снизу не поможет?

Код: Выделить всё

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" 
    android:orientation="vertical" 
    android:layout_width="match_parent" 

    android:layout_height="match_parent" 

    android:id="@+id/lbody"> 
Т.е. лайяут в котором у тебя лежат другие лаяуты в которых лежат кнопки и пр. пытается занять по высоте match_parent, вероятно, "растягивая" для этого "средний" лайяут, т.к. сумма высот лаяутов меньше высоты экрана.
Тебе действительно нужна вся высота? Тогда скажи ему какими полями у каких лаяутов ему добавить суммарной высоты

aleksbim
Сообщения: 81
Зарегистрирован: 02 фев 2013, 02:52

Re: Урок 105. Android 3. Fragments. Динамическая работа

Сообщение aleksbim » 24 авг 2016, 23:58

Не получается запустить скопированный код урока в eclipse.

Multiple annotations found at this line:
- Element type "LinearLayout" must be followed by either attribute specifications, ">"
or "/>".
- error: Error parsing XML: not well-formed (invalid token)
Подскажите пжл. что не так?
Вложения
Снимок.JPG
Снимок.JPG (42.82 КБ) 5770 просмотров

Ответить