如何在 Android Studio 中将 ListView 更改为 RecyclerView?
Posted
技术标签:
【中文标题】如何在 Android Studio 中将 ListView 更改为 RecyclerView?【英文标题】:How to change ListView to RecyclerView in Android Studio? 【发布时间】:2020-08-11 23:44:03 【问题描述】:不知道怎么用RecyclerView来代替ListView。任何人都可以帮助我吗?谢谢你。我在不同的在线平台上找到了很多资源,但我不知道如何更改我的代码。当我尝试更改我的代码时,它不起作用。
代码如下:
MainActivity.java
public class MainActivity extends AppCompatActivity
private String TAG = MainActivity.class.getSimpleName();
private ProgressDialog pDialog;
private ListView lv;
// URL to get contacts JSON
private static String url = "https://api.androidhive.info/contacts/";
ArrayList<HashMap<String, String>> contactList;
@Override
protected void onCreate(Bundle savedInstanceState)
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
contactList = new ArrayList<>();
lv = (ListView) findViewById(R.id.list);
new GetContacts().execute();
/**
* Async task class to get json by making HTTP call
*/
private class GetContacts extends AsyncTask<Void, Void, Void>
@Override
protected void onPreExecute()
super.onPreExecute();
// Showing progress dialog
pDialog = new ProgressDialog(MainActivity.this);
pDialog.setMessage("Please wait...");
pDialog.setCancelable(false);
pDialog.show();
@Override
protected Void doInBackground(Void... arg0)
HttpHandler sh = new HttpHandler();
// Making a request to url and getting response
String jsonStr = sh.makeServiceCall(url);
Log.e(TAG, "Response from url: " + jsonStr);
if (jsonStr != null)
try
JSONObject jsonObj = new JSONObject(jsonStr);
// Getting JSON Array node
JSONArray contacts = jsonObj.getJSONArray("contacts");
// looping through All Contacts
for (int i = 0; i < contacts.length(); i++)
JSONObject c = contacts.getJSONObject(i);
String id = c.getString("id");
String name = c.getString("name");
String email = c.getString("email");
String address = c.getString("address");
String gender = c.getString("gender");
// Phone node is JSON Object
JSONObject phone = c.getJSONObject("phone");
String mobile = phone.getString("mobile");
String home = phone.getString("home");
String office = phone.getString("office");
// tmp hash map for single contact
HashMap<String, String> contact = new HashMap<>();
// adding each child node to HashMap key => value
contact.put("id", id);
contact.put("name", name);
contact.put("email", email);
contact.put("mobile", mobile);
// adding contact to contact list
contactList.add(contact);
catch (final JSONException e)
Log.e(TAG, "Json parsing error: " + e.getMessage());
runOnUiThread(new Runnable()
@Override
public void run()
Toast.makeText(getApplicationContext(),
"Json parsing error: " + e.getMessage(),
Toast.LENGTH_LONG)
.show();
);
else
Log.e(TAG, "Couldn't get json from server.");
runOnUiThread(new Runnable()
@Override
public void run()
Toast.makeText(getApplicationContext(),
"Couldn't get json from server. Check LogCat for possible errors!",
Toast.LENGTH_LONG)
.show();
);
return null;
@Override
protected void onPostExecute(Void result)
super.onPostExecute(result);
// Dismiss the progress dialog
if (pDialog.isShowing())
pDialog.dismiss();
ListAdapter adapter = new SimpleAdapter(
MainActivity.this, contactList,
R.layout.list_item, new String[]"name", "email",
"mobile", new int[]R.id.name,
R.id.email, R.id.mobile);
lv.setAdapter(adapter);
HttpHandler.java
public class HttpHandler
private static final String TAG = HttpHandler.class.getSimpleName();
public HttpHandler()
public String makeServiceCall(String reqUrl)
String response = null;
try
URL url = new URL(reqUrl);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
// read the response
InputStream in = new BufferedInputStream(conn.getInputStream());
response = convertStreamToString(in);
catch (MalformedURLException e)
Log.e(TAG, "MalformedURLException: " + e.getMessage());
catch (ProtocolException e)
Log.e(TAG, "ProtocolException: " + e.getMessage());
catch (IOException e)
Log.e(TAG, "IOException: " + e.getMessage());
catch (Exception e)
Log.e(TAG, "Exception: " + e.getMessage());
return response;
private String convertStreamToString(InputStream is)
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line;
try
while ((line = reader.readLine()) != null)
sb.append(line).append('\n');
catch (IOException e)
e.printStackTrace();
finally
try
is.close();
catch (IOException e)
e.printStackTrace();
return sb.toString();
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.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_
android:layout_
tools:context="hk.edu.ouhk.android.jsonparsing.MainActivity">
<ListView
android:id="@+id/list"
android:layout_
android:layout_
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>
list_item.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_
android:layout_
android:orientation="vertical"
android:padding="16dip">
<TextView
android:id="@+id/name"
android:layout_
android:layout_
android:paddingBottom="2dip"
android:paddingTop="6dip"
android:textColor="@color/colorPrimaryDark"
android:textSize="16sp"
android:textStyle="bold" />
<TextView
android:id="@+id/email"
android:layout_
android:layout_
android:paddingBottom="2dip"
android:textColor="#5d5d5d" />
<TextView
android:id="@+id/mobile"
android:layout_
android:layout_
android:textColor="#686868"
android:textStyle="bold" />
</LinearLayout>
【问题讨论】:
你说的不起作用是什么意思?你遇到了什么错误? 【参考方案1】:因为您从 url 获取数据似乎没有问题,并且您已经成功地从数据中创建了一个 Arraylist
现在要遵循的步骤 1.将recyclerview添加到活动的xml中 2. 做一个布局,你想如何在 recyclerview 项目中显示数据 3. 然后你需要制作一个适配器来接收你提供的数据并将其绑定到 回收站视图 4. 然后将适配器添加到您的回收站视图中
我附上了我不久前为我制作的简单回收站视图。它很简单且不言自明。否则你可以评论我会解释更多
Main Activity
public class MainActivity extends AppCompatActivity
ArrayList<String> moviesList;
RecyclerView recyclerView;
RecyclerAdapter recyclerAdapter;
@Override
protected void onCreate(Bundle savedInstanceState)
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
moviesList=new ArrayList<>();
recyclerView=findViewById(R.id.recyclerView);
recyclerAdapter=new RecyclerAdapter(moviesList);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
recyclerView.setAdapter(recyclerAdapter);
moviesList.add("Kapil");
moviesList.add("Kapil");
moviesList.add("Kapil");
moviesList.add("Kapil");
moviesList.add("Kapil");
moviesList.add("Kapil");
moviesList.add("Kapil");
RecyclerAdapter in this we are creating custom viewholder for us
public class RecyclerAdapter extends RecyclerView.Adapter<RecyclerAdapter.ViewHolder>
public RecyclerAdapter(ArrayList<String> moviesList)
this.moviesList = moviesList;
ArrayList<String> moviesList;
@NonNull
@Override
public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType)
LayoutInflater layoutInflater=LayoutInflater.from(parent.getContext());
View view=layoutInflater.inflate(R.layout.row_layout,parent,false);
ViewHolder viewHolder= new ViewHolder(view);
return viewHolder;
@Override
public void onBindViewHolder(@NonNull ViewHolder holder, int position)
holder.rowTextView.setText(String.valueOf(position));
holder.textView.setText(moviesList.get(position));
@Override
public int getItemCount()
return moviesList.size();
class ViewHolder extends RecyclerView.ViewHolder
ImageView imageView;
TextView textView,rowTextView;
public ViewHolder(@NonNull View itemView)
super(itemView);
imageView=itemView.findViewById(R.id.imageView);
textView=itemView.findViewById(R.id.textView);
rowTextView=itemView.findViewById(R.id.rowTextView);
This is layout for the item which I want to show in recycler view
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.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_
android:layout_>
<ImageView
android:id="@+id/imageView"
android:layout_
android:layout_
android:layout_marginStart="22dp"
android:layout_marginTop="16dp"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:srcCompat="@drawable/ic_launcher_background" />
<TextView
android:id="@+id/textView"
android:layout_
android:layout_
android:layout_marginStart="32dp"
android:layout_marginTop="22dp"
android:text="TextView"
android:textAppearance="@style/TextAppearance.AppCompat.Large"
app:layout_constraintStart_toEndOf="@+id/imageView"
app:layout_constraintTop_toTopOf="parent" />
<TextView
android:id="@+id/rowTextView"
android:layout_
android:layout_
android:layout_marginStart="33dp"
android:layout_marginTop="16dp"
android:text="TextView"
app:layout_constraintStart_toEndOf="@+id/imageView"
app:layout_constraintTop_toBottomOf="@+id/textView" />
</androidx.constraintlayout.widget.ConstraintLayout>
只需将您的数组列表传递给它。和我一样
【讨论】:
【参考方案2】:基本上你需要用 ViewHolder 模式创建 RecyclerViewAdapter,只需简单地将 ListView 替换为 RecyclerView
【讨论】:
但是不知道ViewHolder怎么写。你能给我一些提示吗?谢谢。 这很简单,只需阅读几篇像这样的初学者帖子grokkingandroid.com/first-glance-androids-recyclerview以上是关于如何在 Android Studio 中将 ListView 更改为 RecyclerView?的主要内容,如果未能解决你的问题,请参考以下文章
如何在 Android Studio Java 中将数组上传到 Firestore 数据
如何在 Android Studio 中将 CSV 文件解析为数组
如何在 Android Studio 项目中将库添加到 Gradle 构建?