Android中的列表(特别是带有CardViews的RecyclerView)如何工作 [英] How Lists (specifically, RecyclerView with CardViews) in Android work

查看:70
本文介绍了Android中的列表(特别是带有CardViews的RecyclerView)如何工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

请原谅我问这个问题,但是我是Android开发的新手,尽管我试图通过developer.android.com网站上的基础知识,但大多数示例(即使他们说它们是为Android Studio)尚未设置为使用Gradle,因此除非将其迁移到Gradle否则就不会构建,并且这样做时它什么都不做,或者会出现大量错误.

Forgive me for asking this question, but I am new to Android development and although I am trying to go through the basics on the developer.android.com website, most of the samples (even though they say they're built for Android Studio) are not already setup to use Gradle and thus do not build unless you migrate them over to Gradle, and when you do that it either doesn't do anything or you get tons of errors.

我一直在尝试学习如何创建列表.

I've been trying to learn how to create Lists.

我从不同的来源阅读了很多有关此的教程.我已经阅读了Android文档.即使我无法构建其中的一些示例,我甚至都阅读了Android示例的源代码.

I've read a bunch of tutorials on this from different sources. I've read the Android documentation. I've even read through the source code of the Android samples even though I couldn't get a few of them to build.

我尝试编写自己的代码,但是我只是不理解在Android中创建List控件/元素/视图并将数据绑定/插入其中的逻辑(由于缺少更好的词).

I've tried writing my own code but I just don't understand the logic (for lack of a better word) behind creating List controls/elements/views in Android and binding/inserting data to them.

我正在尝试创建 CardView 列表.我不明白如何创建列表(任何类型)并在运行时将 items 插入其中(例如,在foreach循环中).我以为CardView是它自己的列表,但事实证明它只是另一个控件/视图,有点像一个列表项,并且您向列表中添加了许多控件/视图.我读过您应该将CardViews放入RecyclerView(我认为是列表)中.但是我尝试过的所有样本甚至都由于错误而无法构建.因此,这只会增加尝试学习事物工作方式时的困惑.

I am trying to create a CardView list. I don't understand how to create a List (of any type) and insert items into it at runtime (in a foreach loop for example). I thought that CardView was a list of its own, but it turns out it's just another control/view, kind of like a list item, and you add many to a list. I've read that you should put CardViews in a RecyclerView (which I think is a list). But all of the samples I've tried don't even build due to errors. So this just adds to the confusion while trying to learn how things work.

例如,如何在运行时通过for/foreach循环创建RecyclerView列表并向其中添加CardView项?

How do I create a RecyclerView list and add CardView items to it at runtime in a for/foreach loop, for example?

推荐答案

我整理了一个示例.到家后,我将通过说明进行更新.

I have put together an example. I will update it with explanation when I get home.

activity_main.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:padding="16dp"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context=".MainActivity">

    <EditText
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="Title"
        android:id="@+id/etTitle" />

    <EditText
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="Description"
        android:id="@+id/etDescription" />

    <Button
        android:id="@+id/btnAddItem"
        android:text="Add Item"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />


    <ListView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:divider="@android:color/transparent"
        android:layout_weight="1"
        android:id="@+id/lvList" />

</LinearLayout>

list_row_layout.xml

<android.support.v7.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="horizontal"
    android:layout_width="match_parent"
    android:layout_margin="8dp"
    android:layout_height="match_parent">

    <LinearLayout
        android:orientation="vertical"
        android:layout_width="match_parent"
        android:layout_height="wrap_content">

        <TextView
            android:id="@+id/txtTitle"
            android:padding="12dp"
            android:layout_width="match_parent"
            android:textColor="@android:color/black"
            android:layout_height="wrap_content" />

        <TextView
            android:id="@+id/txtDescription"
            android:padding="12dp"
            android:layout_width="match_parent"
            android:textColor="@android:color/black"
            android:layout_height="wrap_content" />
    </LinearLayout>
</android.support.v7.widget.CardView>

ListData.java

public class ListData {
    String title;
    String Description;

    public String getTitle() {
        return title;
    }

    public void setTitle(String title) {
        this.title = title;
    }

    public String getDescription() {
        return Description;
    }

    public void setDescription(String description) {
        Description = description;
    }
}

ListAdapter

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;

public class ListAdapter extends BaseAdapter {
    ArrayList<ListData> myList = new ArrayList<ListData>();
    Context context;

    public ListAdapter(Context context, ArrayList<ListData> myList) {
        this.myList = myList;
        this.context = context;
    }

    @Override
    public int getCount() {
        return myList.size();
    }

    @Override
    public ListData getItem(int position) {
        return myList.get(position);
    }

    @Override
    public long getItemId(int position) {
        return 0;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        ListViewHolder view = (ListViewHolder) convertView;
        if (view == null) {
            view = new ListViewHolder(context);
        }
        ListData log = getItem(position);
        view.setLog(log);
        return view;
    }
}

ListViewHolder

import android.content.Context;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.widget.LinearLayout;
import android.widget.TextView;


public class ListViewHolder extends LinearLayout {
    Context mContext;
    ListData mLog;

    public ListViewHolder(Context context) {
        super(context);
        mContext = context;
        setup();
    }

    public ListViewHolder(Context context, AttributeSet attrs) {
        super(context, attrs);
        mContext = context;
        setup();
    }

    private void setup() {
        LayoutInflater inflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        inflater.inflate(R.layout.list_row_layout, this);
    }

    public void setLog(ListData log) {
        mLog = log;
        TextView tvTitle = (TextView) findViewById(R.id.txtTitle);
        tvTitle.setText(mLog.getTitle() + "");
        TextView tvDescription = (TextView) findViewById(R.id.txtDescription);
        tvDescription.setText(mLog.getDescription() + "");
    }
}

MainActivity

import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Toast;

import java.util.ArrayList;


public class MainActivity extends ActionBarActivity {
    Button btnAddItem;
    ListView lvList;
    ArrayList<ListData> myList = new ArrayList<ListData>();
    ListAdapter listAdapter;
    EditText etTitle, etDescription;
    String title = "", description = "";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        lvList = (ListView) findViewById(R.id.lvList);
        listAdapter = new ListAdapter(MainActivity.this, myList);
        lvList.setAdapter(listAdapter);
        etTitle = (EditText) findViewById(R.id.etTitle);
        etDescription = (EditText) findViewById(R.id.etDescription);
        btnAddItem = (Button) findViewById(R.id.btnAddItem);
        btnAddItem.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                title = etTitle.getText().toString();
                description = etDescription.getText().toString();
                if (title.length() == 0) {
                    title = "Not Title";
                }
                if (description.length() == 0) {
                    description = "No Description";
                }
                ListData mLog = new ListData();
                mLog.setTitle(title);
                mLog.setDescription(description);
                myList.add(mLog);
                listAdapter.notifyDataSetChanged();
            }
        });
        lvList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                ListData mLog = listAdapter.getItem(position);
                Toast.makeText(MainActivity.this, "Title: " + mLog.getTitle() + "  Description: " + mLog.getDescription(), Toast.LENGTH_LONG).show();
            }
        });
    }
}

成绩

apply plugin: 'com.android.application'

android {
    compileSdkVersion 21
    buildToolsVersion "21.1.2"

    defaultConfig {
        applicationId "your application id"
        minSdkVersion 14
        targetSdkVersion 21
        versionCode 1
        versionName "1.0"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    compile 'com.android.support:appcompat-v7:21.0.3'
    compile 'com.android.support:cardview-v7:21.+'
}

应该是什么样子

这篇关于Android中的列表(特别是带有CardViews的RecyclerView)如何工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆