Andrey
Andrey

Reputation: 31

Can't dynamically add view

My question is about is about .addView(). I can't add view in LinearLayout. I have same codes in two different fragments. First runs it properly. May be because there constant number of views. Second doesn't add Views at all. I guess there is some problem in .xml files. Could you help me here?

package com.andrey.proparser;

import android.graphics.drawable.TransitionDrawable;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import static android.support.constraint.Constraints.TAG;

public class SearchFragment extends Fragment {

    public static final String URL = "http://knijky.ru/search?search_api_views_fulltext=";

    int counter = 0;

    Animation anim1 = null;
    Animation anim2 = null;
    EditText editText;
    Button button;
    ImageView image;

    List<View> all_Boocks = new ArrayList<>();
    List<String> books_link = new ArrayList<>();
    List<String> book_names = new ArrayList<>();
    List<String> book_desription = new ArrayList<>();




    @Nullable
    @Override
    public View onCreateView(@Nullable LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_search, null);
        editText = view.findViewById(R.id.search_text);
        image = view.findViewById(R.id.search_image);
        anim1 = AnimationUtils.loadAnimation(getActivity(), R.anim.animation);
        anim2 = AnimationUtils.loadAnimation(getActivity(), R.anim.rising);
        final TransitionDrawable transition = (TransitionDrawable) image.getBackground();
        editText.setOnKeyListener(new View.OnKeyListener() {
            @Override
            public boolean onKey(View view, int i, KeyEvent keyEvent) {
                if (keyEvent.getAction() == KeyEvent.ACTION_DOWN)
                {
                    switch (i)
                    {
                        case KeyEvent.KEYCODE_ENTER:
                            image.startAnimation(anim1);
                            editText.startAnimation(anim2);
                            transition.startTransition(650);
                            DoStaff();
                            return true;
                        default:
                            break;
                    }
                }
                return false;
            }
        });



        return view;
    }

    private class MyTask extends AsyncTask<Void,Void,Void> {
        String url = URL + editText.getText();
        @Override
        protected Void doInBackground(Void... voids) {

            try {
                Document doc = Jsoup.connect(url).get();
                Elements results = doc.select("span.field-content > a");
                Elements description = doc.select("div.views-field views-field-title > span.field-content" );
                for (Element link : results)
                    if(link.attr("href").contains("/books/")){
                        books_link.add("http://knijky.ru/" + link.attr("href"));
                        book_names.add(link.text());
                    }
                counter = books_link.size()/2;
            } catch (IOException e) {
                e.printStackTrace();
            }

            return null;
        }

        @Override
        protected void onPostExecute(Void aVoid) {
           final LinearLayout linear = getLayoutInflater().inflate(R.layout.fragment_search, null).findViewById(R.id.linear_search);
            for (int i = 0; i < counter; i++) {
                final View view_read = getLayoutInflater().inflate(R.layout.read_book_button, null);
                TextView name = view_read.findViewById(R.id.bookName);
                name.setText(book_names.get(i));
                all_Boocks.add(view_read);
                linear.addView(view_read);
                Log.d(TAG, String.valueOf(i));
            }
            Log.d(TAG, String.valueOf(all_Boocks.size()));
        }


    }

    public void DoStaff(){
        new MyTask().execute();
    }



}

This is fragment_search.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:fresco="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent" android:layout_height="match_parent">
    <EditText
        android:id="@+id/search_text"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:singleLine="true"
        android:layout_centerVertical="true"
        android:background="@android:color/transparent"
        android:layout_marginStart="30dp"
        android:hint="Для поиска нажмите Enter"/>


    <ImageView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:background="@drawable/transition"
        android:id="@+id/search_image"
        android:layout_marginStart="30dp"
        android:layout_centerInParent="true"/>



    <ScrollView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/search_image">

        <LinearLayout
            android:id="@+id/linear_search"
            android:orientation="vertical"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginTop="10dp">
        </LinearLayout>

    </ScrollView>

</RelativeLayout>

This is read_book_button.xml

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


    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textSize="26dp"
        android:text="Some text"
        android:id="@+id/bookName"
        android:layout_alignParentTop="true"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true"
        android:layout_toStartOf="@+id/read_btn"
        android:layout_toLeftOf="@+id/read_btn"
        android:layout_marginLeft="20dp"
        />

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/bookName"
        android:id="@+id/bookDescription"
        android:text="Description"
        android:layout_marginLeft="20dp"
        android:layout_toStartOf="@+id/read_btn"
        android:layout_toLeftOf="@+id/read_btn"
        android:layout_alignParentLeft="true"
        />

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentRight="true"
        android:layout_alignParentEnd="true"
        android:background="@drawable/read_btn"
        android:id="@+id/read_btn"
        android:layout_marginTop="10dp"
        />
</RelativeLayout>

Upvotes: 2

Views: 67

Answers (1)

Mirza Ahmed Baig
Mirza Ahmed Baig

Reputation: 5865

Try to implement in the following way:

public class SearchFragment extends Fragment {

    ImageView imageView;
    LinearLayout layout;

    private void onPostExecute() {
        final View view_read = getLayoutInflater().inflate(R.layout.read_book_button, null);
        TextView name = view_read.findViewById(R.id.bookName);
        name.setText("kushdfkjgskdf");
        layout.addView(view_read);
    }

    @Override
    public View onCreateView(@Nullable LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.search_fragment, null);

        imageView = view.findViewById(R.id.search_image);
        layout = view.findViewById(R.id.linear_search);
        imageView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                onPostExecute();
            }
        });
        return view;
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
    }
}

here I removed your logic, instead of using inflator to get linear layout you can do as what I did

Upvotes: 3

Related Questions