При попытке добавить выбранные виды изображений с помощью (OnItemClickListener) между фрагментами во втором ImageView происходит сбой приложения - PullRequest
0 голосов
/ 14 ноября 2018

Я пытаюсь добавить и показать несколько представлений изображений, существующих в фрагменте, другому в том же упражнении с помощью OnItemClickListener на GridView.

Мне удалось добавить первый вид изображения, но когда я добавляю второй, приложение вылетает. Кстати, я добавляю виды изображений в линейный макет в режиме горизонтальной прокрутки.

Вот макет первого фрагмента:

<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:id="@+id/content_fragment_id"
    >
    
        <GridView
            android:id="@+id/items_id_gridView"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_centerInParent="true"
            android:columnWidth="100dp"
            android:minHeight="40dp"
            android:paddingTop="5dp"
            android:paddingBottom="5dp"
            android:numColumns="auto_fit"
            android:horizontalSpacing="10.0dip"
            android:verticalSpacing="10.0dip"
            android:cacheColorHint="#00000000"
            android:gravity="center_horizontal"
            android:requiresFadingEdge="vertical"
            />
    
    </RelativeLayout>

Компоновка второго фрагмента:

<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="horizontal"
    >
    <ImageButton
        android:id="@+id/play_button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:src="@drawable/play_36dp"
        android:layout_alignParentRight="true"
        android:layout_alignParentEnd="true"
        android:contentDescription="@string/play_button" />


    <HorizontalScrollView
        android:id="@+id/sentenceBarScrollView"
        android:layout_width="fill_parent"
        android:layout_height="104dp"
        android:layout_toLeftOf="@id/play_button"
        android:layout_toStartOf="@id/play_button"
        android:padding="1dp"
        >
        <LinearLayout
            android:id="@+id/sentence_bar"
            android:layout_width="wrap_content"
            android:layout_height="match_parent"
            android:padding="2dp"
            android:orientation="horizontal"
            >

        </LinearLayout>


    </HorizontalScrollView>

</RelativeLayout>

Макет основного вида деятельности:

<android.support.constraint.ConstraintLayout
    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:context=".Home"

    >
<RelativeLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <android.support.v7.widget.CardView
        android:id="@+id/sentence_layout"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        >

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="100dp"
            android:orientation="vertical">
            <fragment
                android:id="@+id/sentenceBarFragment"
                android:name="ye.com.ebra.contentfragments.SentenceBarFragment"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"

                />
        </LinearLayout>
    </android.support.v7.widget.CardView>

    <RelativeLayout
        android:id="@+id/content_Layout"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_below="@+id/sentence_layout"
        android:padding="5dp"
        >
    <!-- put contents fragments here :) -->
    </RelativeLayout>
</RelativeLayout>


</android.support.constraint.ConstraintLayout>

класс первого фрагмента.

sendItemToSentenceBar connector;

//for retrieving the values of the image stored in database 
private Item item;

static  ArrayList<Integer> back;

@Override
public void onActivityCreated(@Nullable Bundle savedInstanceState) {
    super.onActivityCreated(savedInstanceState);

back=new ArrayList<>();
    DBConnection dbConnection= new DBConnection(getActivity());
    GridView gridView=getActivity().findViewById(R.id.items_id_gridView);

    final ArrayList<Item> items2=new ArrayList<>(dbConnection.getAll(Cat_id));

    ContentAdapter dataAdapter=new ContentAdapter(getActivity(),items2);
    gridView.setAdapter(dataAdapter);

gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {

        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id)
        {
            item=items2.get(position);
            if(item.getType().equals("Category"))
            {
                back.add(Cat_id);
                changeFragment(item.getID());
                AddNewDialogFragment.Cat_id=item.getID();

            }else {
                speak(item.getName());
                connector.sendData(item);
            }
        }
    });
}

и я использую интерфейс для передачи данных из OnItemClickListener в другой фрагмент с помощью "connector.sendData (item);"

Вот интерфейс:

public interface sendItemToSentenceBar {
// send item to the sentence bar fragment :)
void sendData(Item item);
}

Тогда в классе другой фрагмент Существует метод AddItem (Item item), который должен добавить представление изображения ко второму фрагменту, первое представление изображения может быть добавлено ко второму, когда приложение просто вылетает:

private ArrayList<Item>  items;

private LinearLayout sentenceLayout;
private View itemView;

private ArrayList<View> itemsViews;
View view;

@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, Bundle savedInstanceState) {
    View sentenceBarFragment=inflater.inflate(R.layout.activity_sentence_bar_fragment,container,false);
    sentenceLayout  =   sentenceBarFragment.findViewById(R.id.sentence_bar);
    itemView        =   inflater.inflate(R.layout.activity_item,sentenceLayout,false);


return  sentenceBarFragment;
}

public void AddItem(Item item){

        TextView name_id = itemView.findViewById(R.id.name_id);
        name_id.setText(item.getName());

        ImageView image_id = itemView.findViewById(R.id.image_id);
        image_id.setImageBitmap(convertByteToBitmap(item.getImage()));
        itemsViews.add(itemView);
        sentenceLayout.addView(itemsViews.get(0));

items.add(item);
    }

Наконец, метод AddItem (Item item) используется в классе основного действия, содержащем оба фрагмента:

@Override
public void sendData(Item item) {
    FragmentManager fragmentManager=getFragmentManager();
    SentenceBarFragment s= (SentenceBarFragment) fragmentManager.findFragmentById(R.id.sentenceBarFragment);
    s.AddItem(item);
}

Здесь Logcat:

E/AndroidRuntime: FATAL EXCEPTION: main
java.lang.IllegalStateException: The specified child already has a parent. You must call removeView() on the child's parent first.
    at android.view.ViewGroup.addViewInner(ViewGroup.java:3378)
    at android.view.ViewGroup.addView(ViewGroup.java:3249)
    at android.view.ViewGroup.addView(ViewGroup.java:3194)
    at android.view.ViewGroup.addView(ViewGroup.java:3170)
    at ye.com.ebra.contentfragments.SentenceBarFragment.AddItem(SentenceBarFragment.java:95)
    at ye.com.ebra.contentfragments.Home.sendData(Home.java:129)
    at ye.com.ebra.contentfragments.ContentFragment$2.onItemClick(ContentFragment.java:83)
    at android.widget.AdapterView.performItemClick(AdapterView.java:298)
    at android.widget.AbsListView.performItemClick(AbsListView.java:1086)
    at android.widget.AbsListView$PerformClick.run(AbsListView.java:2855)
    at android.widget.AbsListView$1.run(AbsListView.java:3529)
    at android.os.Handler.handleCallback(Handler.java:615)
    at android.os.Handler.dispatchMessage(Handler.java:92)
    at android.os.Looper.loop(Looper.java:137)
    at android.app.ActivityThread.main(ActivityThread.java:4745)
    at java.lang.reflect.Method.invokeNative(Native Method)
    at java.lang.reflect.Method.invoke(Method.java:511)
    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:786)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
    at dalvik.system.NativeStart.main(Native Method)

из Logcat, я мог бы определить эти ошибки:

at ye.com.ebra.contentfragments.SentenceBarFragment.AddItem(SentenceBarFragment.java:95)

, который находится в классе второго фрагмента, в методе AddItem (Item item)

sentenceLayout.addView(itemsViews.get(0));

.

at ye.com.ebra.contentfragments.Home.sendData(Home.java:129)

который находится в классе основной деятельности, в используемом методе sendData (элемент данных)

s.AddItem(item);

.

at ye.com.ebra.contentfragments.ContentFragment$2.onItemClick(ContentFragment.java:83)

, который находится в классе первого фрагмента, в OnItemClickListener: connector.sendData (пункт);

Извините за длинный пост, но я действительно застрял здесь

1 Ответ

0 голосов
/ 14 ноября 2018

Вы, кажется, неоднократно модифицируете и добавляете один и тот же объект item_view, накачанный в методе onCreateView(...). Мне кажется, что вам нужно надувать новый объект каждый раз, когда вы вызываете «AddItem».

Существует также возможная проблема с добавлением представлений в список itemViews, но с неоднократным добавлением первого представления в списке (т. Е. Не того, которое вы только что добавили).

Так что SentenceBarFragment может выглядеть так:

private ArrayList<Item>  items;

private LinearLayout sentenceLayout;

private ArrayList<View> itemsViews;

@Nullable
@Override    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, Bundle savedInstanceState) {
    View sentenceBarFragment=inflater.inflate(R.layout.activity_sentence_bar_fragment,container,false);
    sentenceLayout  =   sentenceBarFragment.findViewById(R.id.sentence_bar);
    return  sentenceBarFragment;
}

public void AddItem(Item item){

    // inflate a new view to be added
    View itemView = LayoutInflater.from(getActivity()).inflate(R.layout.activity_item,sentenceLayout,false);

    TextView name_id = itemView.findViewById(R.id.name_id);
    name_id.setText(item.getName());

    ImageView image_id = itemView.findViewById(R.id.image_id);
    image_id.setImageBitmap(convertByteToBitmap(item.getImage()));

    // add the view you just inflated
    itemsViews.add(itemView);
    sentenceLayout.addView(itemView);  // or addView(itemViews.get(itemViews.size()-1))
    items.add(item);
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...