#android
#Android
Вопрос:
Мне нужно, чтобы кто-нибудь сказал мне, каковы основные необходимые библиотеки для базового приложения, которое отображает список массивов в recyclerview. Я выполнил все шаги, и в Android studio нет ошибок, но приложение не показало «Строки» из массива, который я передал адаптеру, оно показывает только цифры от 1 до 20 без каких-либо букв. это основной файл активности
package com.android.a0202;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.content.Context;
import android.os.Bundle;
import android.view.MenuItem;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import java.util.Scanner;
public class MainActivity extends AppCompatActivity {
/*
* References to RecyclerView and Adapter to reset the list to its
* "pretty" state when the reset menu item is clicked.
*/
private GreenAdapter mAdapter;
private RecyclerView mNumbersList;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final String[] NUM_LIST_ITEMS = new String[20];
NUM_LIST_ITEMS[0]="8451";
NUM_LIST_ITEMS[1]="85";
NUM_LIST_ITEMS[2]="852";
NUM_LIST_ITEMS[3]="526585";
NUM_LIST_ITEMS[4]="84565";
NUM_LIST_ITEMS[7]="rctvybun";
NUM_LIST_ITEMS[8]="zxctvybunmi";
NUM_LIST_ITEMS[9]="drtyuhi";
NUM_LIST_ITEMS[10]="xerctvybunm";
NUM_LIST_ITEMS[11]="ercvtyn";
NUM_LIST_ITEMS[12]="lkxghj";
NUM_LIST_ITEMS[13]="85";
NUM_LIST_ITEMS[14]="534546";
NUM_LIST_ITEMS[15]="454645";
NUM_LIST_ITEMS[16]="xcvbnj";
NUM_LIST_ITEMS[17]="cv";
NUM_LIST_ITEMS[18]="cvb";
NUM_LIST_ITEMS[19]="/";
/*
* Using findViewById, we get a reference to our RecyclerView from xml. This allows us to
* do things like set the adapter of the RecyclerView and toggle the visibility.
*/
mNumbersList = (RecyclerView) findViewById(R.id.rv_numbers);
/*
* A LinearLayoutManager is responsible for measuring and positioning item views within a
* RecyclerView into a linear list. This means that it can produce either a horizontal or
* vertical list depending on which parameter you pass in to the LinearLayoutManager
* constructor. By default, if you don't specify an orientation, you get a vertical list.
* In our case, we want a vertical list, so we don't need to pass in an orientation flag to
* the LinearLayoutManager constructor.
*
* There are other LayoutManagers available to display your data in uniform grids,
* staggered grids, and more! See the developer documentation for more details.
*/
LinearLayoutManager layoutManager = new LinearLayoutManager(this);
mNumbersList.setLayoutManager(layoutManager);
/*
* Use this setting to improve performance if you know that changes in content do not
* change the child layout size in the RecyclerView
*/
mNumbersList.setHasFixedSize(true);
/*
* The GreenAdapter is responsible for displaying each item in the list.
*/
mAdapter = new GreenAdapter(NUM_LIST_ITEMS);
mNumbersList.setAdapter(mAdapter);
}
}
и это файл адаптера
package com.android.a0202;
import android.content.Context;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import androidx.recyclerview.widget.RecyclerView;
public class GreenAdapter extends RecyclerView.Adapter<GreenAdapter.NumberViewHolder> {
// final private ListItemClickListener monClicklistener;
// TODO (1) Create a layout resource in res/layout/ called number_list_item.xml
// Do steps 2 - 11 within number_list_item.xml
// TODO (2) Make the root layout a FrameLayout
// TODO (3) Make the width match_parent and the height wrap_content
// TODO (4) Set the padding to 16dp
// TODO (5) Add a TextView as the only child of the FrameLayout
// TODO (6) Give the TextView an ID "@ id/tv_item_number"
// TODO (7) Set the height and width to wrap_content
// TODO (8) Align the TextView to the start of the parent
// TODO (9) Center the TextView vertically in the layout
// TODO (10) Set the font family to monospace
// TODO (11) Set the text size to 42sp
private static final String TAG = GreenAdapter.class.getSimpleName();
private String[] mNumberItems;
// public interface ListItemClickListener {
// void onListItemClick(int clickedItemIndex);
//}
/**
* Constructor for GreenAdapter that accepts a number of items to display and the specification
* for the ListItemClickListener.
*
* @param numberOfItems Number of items to display in list
*/
public GreenAdapter(String[] numberOfItems) {
mNumberItems = numberOfItems;
// monClicklistener =listener;
}
/**
*
* This gets called when each new ViewHolder is created. This happens when the RecyclerView
* is laid out. Enough ViewHolders will be created to fill the screen and allow for scrolling.
*
* @param viewGroup The ViewGroup that these ViewHolders are contained within.
* @param viewType If your RecyclerView has more than one type of item (which ours doesn't) you
* can use this viewType integer to provide a different layout. See
*
* for more details.
* @return A new NumberViewHolder that holds the View for each list item
*/
@Override
public NumberViewHolder onCreateViewHolder(ViewGroup viewGroup, int viewType) {
Context context = viewGroup.getContext();
int layoutIdForListItem = R.layout.number_list_item;
LayoutInflater inflater = LayoutInflater.from(context);
boolean shouldAttachToParentImmediately = false;
View view = inflater.inflate(layoutIdForListItem, viewGroup, shouldAttachToParentImmediately);
NumberViewHolder viewHolder = new NumberViewHolder(view);
return viewHolder;
}
/**
* OnBindViewHolder is called by the RecyclerView to display the data at the specified
* position. In this method, we update the contents of the ViewHolder to display the correct
* indices in the list for this particular position, using the "position" argument that is conveniently
* passed into us.
*
* @param holder The ViewHolder which should be updated to represent the contents of the
* item at the given position in the data set.
* @param position The position of the item within the adapter's data set.
*/
@Override
public void onBindViewHolder(NumberViewHolder holder, int position) {
Log.d(TAG, "#" position);
holder.bind(position);
}
/**
* This method simply returns the number of items to display. It is used behind the scenes
* to help layout our Views and for animations.
*
* @return The number of items available in our forecast
*/
@Override
public int getItemCount() {
return 20;
}
public class NumberViewHolder extends RecyclerView.ViewHolder
// implements View.OnClickListener
{
private TextView listItemNumberView ;
public NumberViewHolder (View itemView){
super(itemView);
listItemNumberView = (TextView) itemView.findViewById(R.id.tv_item_number);
}
void bind (int listIndex){
listItemNumberView.setText(String.valueOf(listIndex));
}
// @Override
//public void onClick(View view){
// int clickedPosition = getAdapterPosition();
// monClicklistener.onListItemClick(clickedPosition);
}
}
// TODO (12) Create a class called NumberViewHolder that extends RecyclerView.ViewHolder
// TODO (13) Within NumberViewHolder, create a TextView variable called listItemNumberView
// TODO (14) Create a constructor for NumberViewHolder that accepts a View called itemView as a parameter
// TODO (15) Within the constructor, call super(itemView) and then find listItemNumberView by ID
// TODO (16) Within the NumberViewHolder class, create a void method called bind that accepts an int parameter called listIndex
// TODO (17) Within bind, set the text of listItemNumberView to the listIndex
// TODO (18) Be careful to get the String representation of listIndex, as using setText with an int does something different
Комментарии:
1. Если перед компиляцией нет ошибок, отсутствующие библиотеки не являются проблемой. Если при его запуске происходит сбой, вам следует просмотреть журнал при его запуске, чтобы понять, почему.
2. Скопируйте и вставьте журнал с вашим вопросом, чтобы мы могли узнать, в чем проблема.
3. @DavidInnocent я исправил первую проблему, появилась другая проблема, пожалуйста, помогите мне здесь
Ответ №1:
Вы должны изменить следующую строку.
listItemNumberView.setText(String.valueOf(listIndex));
К следующему:
listItemNumberView.setText(mNumberItems[listIndex]);
Вы не получили конкретный элемент из списка.
Попробуйте.