Android Studio 中带有 imageview 的 listview

Posted

技术标签:

【中文标题】Android Studio 中带有 imageview 的 listview【英文标题】:listview with imageview in Android Studio 【发布时间】:2019-07-26 06:31:15 【问题描述】:

我是 android Studio 的新手,我想尝试使用如下所示左侧图片的列表视图。我设法用一个简单的列表项制作了这样一个列表,但是当我用一个 ActivityList 更改简单的项目列表时,它就不再起作用了。

如何更改 ArrayList 以将图像视图与名称结合起来?我认为可以通过使用包含图像视图和名称而不是字符串的新类来实现。

代码:

public class MainActivity extends AppCompatActivity 
    @Override
    protected void onCreate(Bundle savedInstanceState) 
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        ListView friendsListView = findViewById(R.id.friendListView);
        final ArrayList<String> myFriends = new ArrayList<String>(asList("Mark","Jane","Sussy","Jan"));
        ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(this,android.R.layout.activity_list_item
                , myFriends);
        friendsListView.setAdapter(arrayAdapter);
        friendsListView.setOnItemClickListener(new AdapterView.OnItemClickListener() 
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) 
                Toast.makeText(getApplicationContext(), "Hello " + myFriends.get(i), Toast.LENGTH_LONG).show();
            
        );
    

【问题讨论】:

不要使用ListView,使用RecyclerView。并且远离旧教程。 【参考方案1】:

activity_main.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_
    android:layout_
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context=".MainActivity"
    android:background="@color/grey_300"
    >

    <android.support.v7.widget.RecyclerView
        android:id="@+id/my_recycler_view"
        android:layout_
        android:layout_
        android:scrollbars="vertical"
        />

</RelativeLayout>

cards_layout.xml 代码:

<android.support.v7.widget.CardView
    android:id="@+id/card_view"
    xmlns:card_view="http://schemas.android.com/apk/res-auto"
    android:layout_
    android:layout_
    card_view:cardBackgroundColor="@color/color_white"
    card_view:cardCornerRadius="10dp"
    card_view:cardElevation="5dp"
    card_view:cardUseCompatPadding="true">

    <LinearLayout
        android:layout_
        android:layout_
        android:orientation="horizontal"
        >

        <ImageView
            android:id="@+id/imageView"
            android:tag="image_tag"
            android:layout_
            android:layout_
            android:layout_margin="5dp"
            android:layout_weight="1"
            android:src="@drawable/ic_launcher"/>

        <LinearLayout
            android:layout_
            android:layout_
            android:layout_marginTop="12dp"
            android:layout_weight="2"
            android:orientation="vertical"
            >

            <TextView
                android:id="@+id/textViewName"
                android:layout_
                android:layout_
                android:layout_gravity="center_horizontal"
                android:layout_marginTop="10dp"
                android:text="Android Name"
                android:textAppearance="?android:attr/textAppearanceLarge"/>

            <TextView
                android:id="@+id/textViewVersion"
                android:layout_
                android:layout_
                android:layout_gravity="center_horizontal"
                android:layout_marginTop="10dp"

                android:text="Android Version"
                android:textAppearance="?android:attr/textAppearanceMedium"/>

        </LinearLayout>
    </LinearLayout>

</android.support.v7.widget.CardView>

menu_main.xml 代码:

<menu 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"
    tools:context=".MainActivity">
    <item android:id="@+id/add_item"
        android:title="Add"
        android:orderInCategory="100"
        app:showAsAction="always"/>
</menu>

MainActivity.java

包 com.journaldev.recyclerviewcardview;

import android.content.Context;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

import java.util.ArrayList;

public class MainActivity extends AppCompatActivity 

    private static RecyclerView.Adapter adapter;
    private RecyclerView.LayoutManager layoutManager;
    private static RecyclerView recyclerView;
    private static ArrayList<DataModel> data;
    static View.OnClickListener myOnClickListener;
    private static ArrayList<Integer> removedItems;

    @Override
    protected void onCreate(Bundle savedInstanceState) 
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        myOnClickListener = new MyOnClickListener(this);

        recyclerView = (RecyclerView) findViewById(R.id.my_recycler_view);
        recyclerView.setHasFixedSize(true);

        layoutManager = new LinearLayoutManager(this);
        recyclerView.setLayoutManager(layoutManager);
        recyclerView.setItemAnimator(new DefaultItemAnimator());

        data = new ArrayList<DataModel>();
        for (int i = 0; i < MyData.nameArray.length; i++) 
            data.add(new DataModel(
                    MyData.nameArray[i],
                    MyData.versionArray[i],
                    MyData.id_[i],
                    MyData.drawableArray[i]
            ));
        

        removedItems = new ArrayList<Integer>();

        adapter = new CustomAdapter(data);
        recyclerView.setAdapter(adapter);
    


    private static class MyOnClickListener implements View.OnClickListener 

        private final Context context;

        private MyOnClickListener(Context context) 
            this.context = context;
        

        @Override
        public void onClick(View v) 
            removeItem(v);
        

        private void removeItem(View v) 
            int selectedItemPosition = recyclerView.getChildPosition(v);
            RecyclerView.ViewHolder viewHolder
                    = recyclerView.findViewHolderForPosition(selectedItemPosition);
            TextView textViewName
                    = (TextView) viewHolder.itemView.findViewById(R.id.textViewName);
            String selectedName = (String) textViewName.getText();
            int selectedItemId = -1;
            for (int i = 0; i < MyData.nameArray.length; i++) 
                if (selectedName.equals(MyData.nameArray[i])) 
                    selectedItemId = MyData.id_[i];
                
            
            removedItems.add(selectedItemId);
            data.remove(selectedItemPosition);
            adapter.notifyItemRemoved(selectedItemPosition);
        
    

    @Override
    public boolean onCreateOptionsMenu(Menu menu) 
        super.onCreateOptionsMenu(menu);
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    

    @Override
    public boolean onOptionsItemSelected(MenuItem item) 
        super.onOptionsItemSelected(item);
        if (item.getItemId() == R.id.add_item) 
           //check if any items to add
            if (removedItems.size() != 0) 
                addRemovedItemToList();
             else 
                Toast.makeText(this, "Nothing to add", Toast.LENGTH_SHORT).show();
            
        
        return true;
    

    private void addRemovedItemToList() 
        int addItemAtListPosition = 3;
        data.add(addItemAtListPosition, new DataModel(
                MyData.nameArray[removedItems.get(0)],
                MyData.versionArray[removedItems.get(0)],
                MyData.id_[removedItems.get(0)],
                MyData.drawableArray[removedItems.get(0)]
        ));
        adapter.notifyItemInserted(addItemAtListPosition);
        removedItems.remove(0);
    

CustomAdapter.java

import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import java.util.ArrayList;

public class CustomAdapter extends RecyclerView.Adapter<CustomAdapter.MyViewHolder> 

    private ArrayList<DataModel> dataSet;

    public static class MyViewHolder extends RecyclerView.ViewHolder 

        TextView textViewName;
        TextView textViewVersion;
        ImageView imageViewIcon;

        public MyViewHolder(View itemView) 
            super(itemView);
            this.textViewName = (TextView) itemView.findViewById(R.id.textViewName);
            this.textViewVersion = (TextView) itemView.findViewById(R.id.textViewVersion);
            this.imageViewIcon = (ImageView) itemView.findViewById(R.id.imageView);
        
    

    public CustomAdapter(ArrayList<DataModel> data) 
        this.dataSet = data;
    

    @Override
    public MyViewHolder onCreateViewHolder(ViewGroup parent,
                                           int viewType) 
        View view = LayoutInflater.from(parent.getContext())
                .inflate(R.layout.cards_layout, parent, false);

        view.setOnClickListener(MainActivity.myOnClickListener);

        MyViewHolder myViewHolder = new MyViewHolder(view);
        return myViewHolder;
    

    @Override
    public void onBindViewHolder(final MyViewHolder holder, final int listPosition) 

        TextView textViewName = holder.textViewName;
        TextView textViewVersion = holder.textViewVersion;
        ImageView imageView = holder.imageViewIcon;

        textViewName.setText(dataSet.get(listPosition).getName());
        textViewVersion.setText(dataSet.get(listPosition).getVersion());
        imageView.setImageResource(dataSet.get(listPosition).getImage());
    

    @Override
    public int getItemCount() 
        return dataSet.size();
    

DataModel.java

public class DataModel 

    String name;
    String version;
    int id_;
    int image;

    public DataModel(String name, String version, int id_, int image) 
        this.name = name;
        this.version = version;
        this.id_ = id_;
        this.image=image;
    

    public String getName() 
        return name;
    

    public String getVersion() 
        return version;
    

    public int getImage() 
        return image;
    

    public int getId() 
        return id_;
    

MyData.java

public class MyData 

    static String[] nameArray = "Cupcake", "Donut", "Eclair", "Froyo", "Gingerbread", "Honeycomb", "Ice Cream Sandwich","JellyBean", "Kitkat", "Lollipop", "Marshmallow";
    static String[] versionArray = "1.5", "1.6", "2.0-2.1", "2.2-2.2.3", "2.3-2.3.7", "3.0-3.2.6", "4.0-4.0.4", "4.1-4.3.1", "4.4-4.4.4", "5.0-5.1.1","6.0-6.0.1";

    static Integer[] drawableArray = R.drawable.cupcake, R.drawable.donut, R.drawable.eclair,
            R.drawable.froyo, R.drawable.gingerbread, R.drawable.honeycomb, R.drawable.ics,
            R.drawable.jellybean, R.drawable.kitkat, R.drawable.lollipop,R.drawable.marsh;

    static Integer[] id_ = 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10;

【讨论】:

【参考方案2】:

你是对的,你需要为你的列表项创建一个模型类;该模型类包含因项目而异的事物;例如在您共享的图片中,列表项具有典型的图片和标题;所以你的模型类。

接下来,不要使用ArrayList&lt;String&gt;,而是使用ArrayList&lt;Item&gt;;其中Item是模型类

第三,您需要创建一个从ArrayAdapter&lt;Item&gt;扩展的自定义适配器;那是因为你不能使用内置的列表项布局“android.R.layout.activity_list_item”,因为它只为你提供了一个字符串;现在你需要附上一张照片。

下面是一个简单的演示

模型类(Item.java)

class Item 

    private int mPicture;
    private String mTitle;

    int getPicture() 
        return mPicture;
    

    Item(int picture, String title) 
        mPicture = picture;
        mTitle = title;
    

    String getTitle() 
        return mTitle;
    


列表视图适配器 (ListViewAdapter.java)

public class ListViewAdapter extends ArrayAdapter<Item> 

    ListViewAdapter(@NonNull Context context, ArrayList<Item> items) 
        super(context, 0, items);
    

    @NonNull
    @Override
    public View getView(int position, @Nullable View convertView, @NonNull ViewGroup parent) 

        View listItem = convertView;
        if (listItem == null) 
            listItem = LayoutInflater.from(getContext()).inflate(R.layout.list_item, parent, false);
        

        // Get the @link Word object located at this position in the list
        Item currentItem = getItem(position);

        ImageView picture = listItem.findViewById(R.id.IvPicture);
        picture.setBackgroundResource(currentItem.getPicture());

        TextView title = listItem.findViewById(R.id.tvTitle);
        title.setText(currentItem.getTitle());

        return listItem;
    


活动类

 public class MainActivity extends AppCompatActivity

       @Override
        protected void onCreate(Bundle savedInstanceState) 
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);

            ArrayList<Item> items = new ArrayList<>();
            items.add(new Item(R.drawable.item1, "Item1"));
            items.add(new Item(R.drawable.item2, "Item2"));
            items.add(new Item(R.drawable.item3, "Item3"));

            ListViewAdapter adapter = new ListViewAdapter(this, items);
            ListView listView = findViewById(R.id.listView);
            listView.setAdapter(adapter);

        

活动布局 (activity_main.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">

    <ListView
        android:id="@+id/listView"
        android:layout_
        android:layout_>
    </ListView>

</LinearLayout>

列表项布局 (list_item.xml)

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/rootView"
    android:layout_
    android:layout_
    android:orientation="horizontal">

    <ImageView
        android:id="@+id/IvPicture"
        android:layout_
        android:layout_ />

    <TextView
        android:id="@+id/tvTitle"
        android:layout_
        android:layout_
        android:text="item" />

</LinearLayout>

你必须在 res/drawable 中有 3 张图片,分别命名为 item1、item2 和 item3

希望这能满足您的需求。

【讨论】:

谢谢。它有帮助。但我还有一个问题。我试图实现它。我必须在这里写什么而不是这一行中的 dummylist ? listItem = LayoutInflater.from(getContext()).inflate(R.layout.dumy_list_item, parent, false);我认为我的代码仍然存在问题。同样在您的 xml 中,您没有列表视图?我认为在我的版本中仍然有问题。我会在下一条评论中写出来。 不客气.. 请告诉我你需要做什么@Tommy Supertramp 我将我的代码添加为新答案。作为 Xml,我使用了您的代码,但前面有一个列表视图 您可以将列表视图放在您在活动类中使用 onCreate() 中的 setContentView() 引用的活动布局 xml 文件中 @TommySupertramp 请检查我的所有布局和 java 文件的更新答案...如果您需要进一步的帮助,请告诉我。请注意,列表项 xml 文件与活动 xml 文件不同(托管您的列表视图)【参考方案3】:
public class MainActivity extends AppCompatActivity 


    @Override
    protected void onCreate(Bundle savedInstanceState) 
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        ListView friendsListView = findViewById(R.id.friendListView);

        final ArrayList<Item> items = new ArrayList<>();
        items.add(new Item(R.drawable.abc, "Item1"));
        items.add(new Item(R.drawable.def, "Item2"));


        ListViewAdapter adapter = new ListViewAdapter(this, items);

        ListView.setAdapter(adapter);

        friendsListView.setOnItemClickListener(new AdapterView.OnItemClickListener() 
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) 

                Toast.makeText(getApplicationContext(), "Hello " + items.get(i), Toast.LENGTH_LONG).show();

            
        );
    

【讨论】:

以上是关于Android Studio 中带有 imageview 的 listview的主要内容,如果未能解决你的问题,请参考以下文章

Android Studio 中带有 imageview 的 listview

Visual Studio 2010 中带有 plsql 的 C# [关闭]

在 Visual Studio 10 中带有库的 PDB 文件

Visual Studio 中带有 ASP.NET Web API 项目的 Angular 项目

Visual Studio 2013 中带有 EF6 的 MySQL 连接器

[Material appbar存在时,Android Studio布局预览不起作用