How Lists (specifically, RecyclerView with CardViews) in Android work

别来无恙 提交于 2019-12-11 03:17:35

问题


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.

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.

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.

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.

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


回答1:


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();
            }
        });
    }
}

Gradle

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.+'
}

What it should look like



来源:https://stackoverflow.com/questions/27908680/how-lists-specifically-recyclerview-with-cardviews-in-android-work

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!