RecyclerView проблема с чертежом - PullRequest
1 голос
/ 20 мая 2019

Я начинаю новую деятельность с RecyclerView из основной деятельности.Элементы отображаются правильно.Но на свитке произошло нечто странное.Элементы не отображаются правильно.Тот же RecyclerView работает правильно, если он находится на главном экране.

enter image description here

это копия кода отсюда

Mainактивность:

public class MainActivity extends AppCompatActivity {

    ImageButton templatButton;

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

        templatButton = findViewById(R.id.template_button);
        templatButton.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                Intent myIntent = new Intent(getBaseContext(), NewActivity.class);
                startActivity(myIntent);
            }
        });
    }

}

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <ImageButton
        android:id="@+id/template_button"
        android:layout_width="180dp"
        android:layout_height="180dp"
        android:layout_marginStart="8dp"
        android:layout_marginBottom="28dp"
        android:background="@drawable/template_icon"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintStart_toStartOf="parent" />

</android.support.constraint.ConstraintLayout>

метод onCreate в новом действии:

    public class NewActivity extends AppCompatActivity {
        RecyclerView recyclerView;

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

                // Initializing list view with the custom adapter
                ArrayList <Item> itemList = new ArrayList<Item>();

                ItemArrayAdapter itemArrayAdapter = new ItemArrayAdapter(R.layout.list_item, itemList);
                recyclerView = (RecyclerView) findViewById(R.id.item_list);
                recyclerView.setLayoutManager(new LinearLayoutManager(this));
                recyclerView.setItemAnimator(new DefaultItemAnimator());
                recyclerView.setAdapter(itemArrayAdapter);

                // Populating list items
                for(int i=0; i<100; i++) {
                    itemList.add(new Item("Item " + i));
                }

            }
}

адаптер массива элементов:

public class ItemArrayAdapter extends RecyclerView.Adapter<ItemArrayAdapter.ViewHolder> {

    //All methods in this adapter are required for a bare minimum recyclerview adapter
    private int listItemLayout;
    private ArrayList<Item> itemList;
    // Constructor of the class
    public ItemArrayAdapter(int layoutId, ArrayList<Item> itemList) {
        listItemLayout = layoutId;
        this.itemList = itemList;
    }

    // get the size of the list
    @Override
    public int getItemCount() {
        return itemList == null ? 0 : itemList.size();
    }


    // specify the row layout file and click for each row
    @Override
    public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(parent.getContext()).inflate(listItemLayout, parent, false);
        ViewHolder myViewHolder = new ViewHolder(view);
        return myViewHolder;
    }

    // load data in each row element
    @Override
    public void onBindViewHolder(final ViewHolder holder, final int listPosition) {
        TextView item = holder.item;
        item.setText(itemList.get(listPosition).getName());
    }

    // Static inner class to initialize the views of rows
    static class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
        public TextView item;
        public ViewHolder(View itemView) {
            super(itemView);
            itemView.setOnClickListener(this);
            item = (TextView) itemView.findViewById(R.id.row_item);
        }
        @Override
        public void onClick(View view) {
            Log.d("onclick", "onClick " + getLayoutPosition() + " " + item.getText());
        }
    }
}

activitiy_list.xml

<?xml version="1.0" encoding="utf-8"?>
<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"
    >
    <android.support.v7.widget.RecyclerView
        android:id="@+id/item_list"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:scrollbars="vertical"
        />
</LinearLayout>

list_item.xml

<?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:layout_height="match_parent">
    <TextView
        android:id="@+id/row_item"
        android:layout_width="match_parent"
        android:layout_height="50dp"
        android:gravity="center"/>
</LinearLayout>

Ответы [ 2 ]

0 голосов
/ 21 мая 2019

1) Сообщите свой адаптер после

  recyclerView.setAdapter(itemArrayAdapter);

  itemArrayAdapter.notifyDataSetChanged();

и убедитесь, что ваша активность не имеет оверлейного макета, пожалуйста, проверьте еще раз.2) На вашем активном переключателе

 templatButton.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            Intent myIntent = new Intent(getBaseContext(), NewActivity.class);
            startActivity(myIntent);
        }
    });

вместо этого используйте

 templatButton.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            Intent myIntent = new Intent(getApplicationContext(), NewActivity.class);
            startActivity(myIntent);
        }
    });

используйте getApplicationContext () , вы можете получить более подробную информацию здесь

0 голосов
/ 21 мая 2019

Установить адаптер после заполнения элементов списка

Заменить вас NewActivity.java кодом с кодом ниже, вставьте после этой строки setContentView (R.layout.activity_list);

        // Initializing list view with the custom adapter

            ArrayList <Item> itemList = new ArrayList<Item>();

            recyclerView = (RecyclerView) findViewById(R.id.item_list);
            recyclerView.setLayoutManager(new LinearLayoutManager(this));
            recyclerView.setItemAnimator(new DefaultItemAnimator());

            //Set Adapter Here
            ItemArrayAdapter itemArrayAdapter = new ItemArrayAdapter(R.layout.list_item, itemList);
            recyclerView.setAdapter(itemArrayAdapter);

            // Populating list items
            for(int i=0; i<100; i++) {
                itemList.add(new Item("Item " + i));
            }

Счастливое кодирование !!!

...