Создание простой программы, которая принимает список из MAX 4 элементов, для оптимизации я выбрал RecyclerView вместо ListView . Я добавил и связал RecyclerView с моими main.xml и MainActivity , создал row.xml , который определяет, как каждая строка внутри RecyclerView будет выглядеть, создаваться и связываться с пользовательским адаптером , который расширяет RecyclerView.Adapter требуемыми методами. Мой код размещен ниже ->
<!-- This is row.xml -->
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:orientation="horizontal"
android:layout_width="match_parent"
android:id="@+id/container_4_row"
android:layout_height="@dimen/media_item_height">
<ImageView
android:id="@+id/cover_art"
android:layout_width="80dp"
android:layout_height="match_parent"
android:layout_marginEnd="50dp"
android:background="@color/colorPrimary"
android:contentDescription="@string/play_item"
android:src="@drawable/ic_action_name" />
<LinearLayout
android:id="@+id/text_container"
android:layout_width="200dp"
android:layout_height="match_parent"
android:orientation="vertical">
<TextView
android:id="@+id/title"
tools:text="The Best Music EVAH1111 FOREVER YOUNG I'M SOME!!!11^H^H"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:maxLines="1"
android:ellipsize="end"
android:textAppearance="?android:attr/textAppearanceMedium"
android:textColor="?android:attr/textColorPrimary"/>
<TextView
android:id="@+id/author"
tools:text="John Doe, his brothers, his sisters, his pets and his more than amazing band"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:maxLines="1"
android:ellipsize="end"
android:textAppearance="?android:attr/textAppearanceSmall"
android:textColor="?android:attr/textColorSecondary"/>
</LinearLayout>
это класс адаптера
public class MyRecycleAdapter extends
RecyclerView.Adapter<MyRecycleAdapter.ViewHolder> {
// Provide a reference to the views for each data item
// Complex data items may need more than one view per item, and
// you provide access to all the views for a data item in a view holder
public static class ViewHolder extends RecyclerView.ViewHolder {
private final TextView mAuthor, mTitle;
private final ImageView aCover;
private final LinearLayout textContainer;
public ViewHolder(View v) {
super(v);
// Define click listener for the ViewHolder's View.
v.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Log.d(TAG, "onClick: Element " + getAdapterPosition() + " clicked.");
}
});
this.textContainer = v.findViewById(R.id.text_container);
this.mAuthor = v.findViewById(R.id.author);
this.mTitle = v.findViewById(R.id.title);
this.aCover = v.findViewById(R.id.cover_art);
}
private TextView getTitle() {
return mTitle;
}
private TextView getAuthor() {
return mAuthor;
}
private ImageView getaCover() {
return aCover;
}
}
// Provide a suitable constructor (depends on the kind of dataset)
public MyRecycleAdapter() {
//mDataset = myDataset;
}
@NonNull
@Override
// Create new views (invoked by the layout manager)
public MyRecycleAdapter.ViewHolder onCreateViewHolder(
@NonNull ViewGroup parent,
int viewType) {
LayoutInflater layoutInflater = LayoutInflater.from(parent.getContext());
Log.d(TAG, "onCreateViewHolder: layoutInflator = ");
// create a new view
View v = layoutInflater.inflate(R.layout.row, parent, false);
return new ViewHolder(v);
}
// Replace the contents of a view (invoked by the layout manager)
@Override
public void onBindViewHolder(final MyRecycleAdapter.ViewHolder viewHolder,
final int position) {
Log.d(TAG, "Element " + position + " set.");
// - get element from your dataset at this position
// - replace the contents of the view with that element
viewHolder.getaCover().setBackgroundColor(Color.RED);
viewHolder.getAuthor().setText("John Doe, his brothers, his sisters");
viewHolder.getTitle().setText("The Best Music EVAH1111");
}
@Override
// Return the size of your dataset (invoked by the layout manager)
public int getItemCount() {
return 4;
}
}
Это в MainActivity
mRecyclerView = findViewById(R.id.recycler);
// Setting improve's performance if changes in content don't alter RecyclerView layout size
mRecyclerView.setHasFixedSize(true);
// use a linear layout manager
mLayoutManager = new LinearLayoutManager(MainActivity.this);
mRecyclerView.setLayoutManager(mLayoutManager);
// not necessary to achieve goal
// String[] mew = new String[]{"mew", "two"};
// specify an adapter (see also next example)
mAdapter = new MyRecycleAdapter(mew);
mRecyclerView.setAdapter(mAdapter);
Мой вопрос: когда я запускаю приложение, RecyclerView.Adapter onBindViewHolder () не распознает дочерние представления внутри родительского держателя представления (который ссылается на row.xml ) .. ..i Я не знаю, почему это не так, потому что раньше у него не было проблем, когда я запускал его без вставки каких-либо литералов или присвоения нуля моему изображению, он был построен правильно, и теперь он случайно настраивается. Я пытался сделать недействительным / очистить кеш и перезапустить AS (не устранил проблемы), я также попытался создать новый фиктивный проект, скопировать и вставить свой код, запустил его без проблем, но у меня есть проблемы в моем основном проекте, который имеет много файлов / вспомогательных классов и т. д., и т. д. *
Ниже приведен журнал ошибок
java.lang.NullPointerException: Attempt to invoke virtual method 'void android.view.View.setBackgroundColor(int)' on a null object reference
at com.example.android.mediasession.ui.auxillary.MyRecycleAdapter.onBindViewHolder(MyRecycleAdapter.java:67)
at com.example.android.mediasession.ui.auxillary.MyRecycleAdapter.onBindViewHolder(MyRecycleAdapter.java:15)
at android.support.v7.widget.RecyclerView$Adapter.onBindViewHolder(RecyclerView.java:6673)
at android.support.v7.widget.RecyclerView$Adapter.bindViewHolder(RecyclerView.java:6714)
at android.support.v7.widget.RecyclerView$Recycler.tryBindViewHolderByDeadline(RecyclerView.java:5647)
at android.support.v7.widget.RecyclerView$Recycler.tryGetViewHolderForPositionByDeadline(RecyclerView.java:5913)
at android.support.v7.widget.RecyclerView$Recycler.getViewForPosition(RecyclerView.java:5752)
at android.support.v7.widget.RecyclerView$Recycler.getViewForPosition(RecyclerView.java:5748)
at android.support.v7.widget.LinearLayoutManager$LayoutState.next(LinearLayoutManager.java:2232)
at android.support.v7.widget.LinearLayoutManager.layoutChunk(LinearLayoutManager.java:1559)
at android.support.v7.widget.LinearLayoutManager.fill(LinearLayoutManager.java:1519)
at android.support.v7.widget.LinearLayoutManager.onLayoutChildren(LinearLayoutManager.java:614)
at android.support.v7.widget.RecyclerView.dispatchLayoutStep2(RecyclerView.java:3812)
at android.support.v7.widget.RecyclerView.onMeasure(RecyclerView.java:3225)
at android.view.View.measure(View.java:21103)
at android.support.constraint.ConstraintLayout.internalMeasureChildren(ConstraintLayout.java:1210)
at android.support.constraint.ConstraintLayout.onMeasure(ConstraintLayout.java:1550)
at android.view.View.measure(View.java:21103)
at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:6462)
at android.widget.FrameLayout.onMeasure(FrameLayout.java:185)
at android.view.View.measure(View.java:21103)
at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:6462)
at android.widget.LinearLayout.measureChildBeforeLayout(LinearLayout.java:1464)
at android.widget.LinearLayout.measureVertical(LinearLayout.java:758)
at android.widget.LinearLayout.onMeasure(LinearLayout.java:640)
at android.view.View.measure(View.java:21103)
at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:6462)
at android.widget.FrameLayout.onMeasure(FrameLayout.java:185)
at com.android.internal.policy.DecorView.onMeasure(DecorView.java:858)
at android.view.View.measure(View.java:21103)
at android.view.ViewRootImpl.performMeasure(ViewRootImpl.java:2573)
at android.view.ViewRootImpl.measureHierarchy(ViewRootImpl.java:1632)
at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:1883)
at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:1512)
at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:7094)
at android.view.Choreographer$CallbackRecord.run(Choreographer.java:927)
at android.view.Choreographer.doCallbacks(Choreographer.java:702)
at android.view.Choreographer.doFrame(Choreographer.java:638)
at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:913)
at android.os.Handler.handleCallback(Handler.java:751)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6836)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1520)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1410)
Приложение прекращено.