简体   繁体   English

Android:如何为卡片视图阵列列表中的每个单个项目设置ID,并且可点击?

[英]Android : How to set ID's for every single items in list of arrays of card view and be clickable?

Hye... I'm new in android development and i'm facing a little bit problem on the android project that I'm in right now. 嗨...我是android开发的新手,我现在在的android项目面临一些问题。 The codes below successfully returning the list of items on the activity_ticket_info.xml layout. 下面的代码成功返回了activity_ticket_info.xml布局上的项目列表。 Since the number of items appeared based on the looping process, how to set an ID on every single items that appeared so afterwards it could be set as clickable items to intent to another activity layout? 由于项目的数量是基于循环过程而出现的,因此如何为出现的每个单个项目设置一个ID,以便以后可以将其设置为可点击的项目,以用于其他活动布局? Please help me to figure this out. 请帮我解决这个问题。 Thanks a lot for the help.. 非常感谢您的帮助..

TicketAdapter.java TicketAdapter.java

 package info.androidhive.navigationdrawer.activity;

import android.content.Context;
import android.content.Intent;
import android.support.v7.widget.CardView;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;

import info.androidhive.navigationdrawer.R;
import info.androidhive.navigationdrawer.ticketfragments.ComboA_TicketFragment;
import info.androidhive.navigationdrawer.ticketfragments.ComboB_TicketFragment;
import info.androidhive.navigationdrawer.ticketfragments.ComboC_TicketFragment;
import info.androidhive.navigationdrawer.ticketfragments.ComboD_TicketFragment;
import info.androidhive.navigationdrawer.ticketfragments.ComboE_TicketFragment;
import info.androidhive.navigationdrawer.ticketfragments.ComboF_TicketFragment;
import info.androidhive.navigationdrawer.ticketfragments.DuckTourTicketFragment;
import info.androidhive.navigationdrawer.ticketfragments.FOneSimulatorFragment;
import info.androidhive.navigationdrawer.ticketfragments.SixDCinemotionTicketFragment;
import info.androidhive.navigationdrawer.ticketfragments.SkyCabBasicTicketFragment;
import info.androidhive.navigationdrawer.ticketfragments.SkyCabExpressLaneTicketFragment;
import info.androidhive.navigationdrawer.ticketfragments.SkyCabPrivateVipGlassTicketFragment;

import static android.R.attr.x;

/**
 * Created by user on 11/14/2016.
 */

public class TicketAdapter extends RecyclerView.Adapter<TicketViewHolder>
{
    String [] name = {
                    "Combo A",
                    "Combo B",
                    "Combo C",
                    "Combo D",
                    "Combo E",
                    "Combo F",
                    "Combo G",
                    "Combo H",
                    "Combo I",
                    "Combo J",
                    "Combo K",
                    "Combo L"
                    };

    Context context;
    LayoutInflater inflater;

    public TicketAdapter(Context context)
    {
        this.context = context;
        inflater = LayoutInflater.from(context);
    }

    @Override
    public TicketViewHolder onCreateViewHolder(ViewGroup parent, int viewType)
    {
        View v = inflater.inflate(R.layout.item_list, parent, false);

        TicketViewHolder viewHolder = new TicketViewHolder(v);
        return viewHolder;
    }

    @Override
    public void onBindViewHolder(TicketViewHolder holder, final int position)
    {
        holder.textTitle.setText(name[position]);
/*      holder.textDesc.setText(desc[position]);*/
        holder.imageView.setOnClickListener(clickListener);
        holder.imageView.setTag(holder);
//        holder.imageView.setId(positionId[position]);

        holder.cardview.setOnClickListener(new View.OnClickListener()
        {
            @Override
            public void onClick(View v)
            {
                switch (position)
                {
                    case 0:
                        Intent intent0 = new Intent(v.getContext(),SkyCabBasicTicketFragment.class);
                        v.getContext().startActivity(intent0);
                        break;
                    case 1:
                        Intent intent1 = new Intent(v.getContext(),SkyCabExpressLaneTicketFragment.class);
                        v.getContext().startActivity(intent1);
                        break;
                    case 2:
                        Intent intent2 = new Intent(v.getContext(),SkyCabPrivateVipGlassTicketFragment.class);
                        v.getContext().startActivity(intent2);
                        break;
                    case 3:
                        Intent intent3 = new Intent(v.getContext(),SixDCinemotionTicketFragment.class);
                        v.getContext().startActivity(intent3);
                        break;
                    case 4:
                        Intent intent4 = new Intent(v.getContext(),DuckTourTicketFragment.class);
                        v.getContext().startActivity(intent4);
                        break;
                    case 5:
                        Intent intent5 = new Intent(v.getContext(),FOneSimulatorFragment.class);
                        v.getContext().startActivity(intent5);
                        break;
                    case 6:
                        Intent intent6 = new Intent(v.getContext(),ComboA_TicketFragment.class);
                        v.getContext().startActivity(intent6);
                        break;
                    case 7:
                        Intent intent7 = new Intent(v.getContext(),ComboB_TicketFragment.class);
                        v.getContext().startActivity(intent7);
                        break;
                    case 8:
                        Intent intent8 = new Intent(v.getContext(),ComboC_TicketFragment.class);
                        v.getContext().startActivity(intent8);
                        break;
                    case 9:
                        Intent intent9 = new Intent(v.getContext(),ComboD_TicketFragment.class);
                        v.getContext().startActivity(intent9);
                        break;
                    case 10:
                        Intent intent10 = new Intent(v.getContext(),ComboE_TicketFragment.class);
                        v.getContext().startActivity(intent10);
                        break;
                    case 11:
                        Intent intent11 = new Intent(v.getContext(),ComboF_TicketFragment.class);
                        v.getContext().startActivity(intent11);
                        break;
                }

            }
        });
    }

    View.OnClickListener clickListener = new View.OnClickListener()
    {
        @Override
        public void onClick(View v)
        {
            TicketViewHolder vholder = (TicketViewHolder) v.getTag();
            int position = vholder.getPosition();

/*            Toast.makeText(context,"You have choose " + position,Toast.LENGTH_LONG ).show();*/

            //Display toast message with each tickets caption details
            Toast.makeText(context,"You have choose " + (name[position]),Toast.LENGTH_LONG ).show();
        }
    };

    @Override
    public int getItemCount()
    {
        return name.length;
    }
}

**UPDATED : I'm trying to implement a switch case statement as above for every single items that need to be navigated to each fragment layout and there is no errors found at all but it doesn't work. **更新:我正在尝试为需要导航到每个片段布局的每个项目实现上述switch case语句,并且根本没有发现任何错误,但是它不起作用。 Could the above switch case statement be the proper way to navigate each items or there is another better way to implement? 上面的switch case语句可能是浏览每个项目的正确方法,还是有另一种更好的实现方法? ** **

TicketInfoActivity.java TicketInfoActivity.java

package info.androidhive.navigationdrawer.activity;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.MenuItem;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;

import info.androidhive.navigationdrawer.R;

import static info.androidhive.navigationdrawer.R.id.name;

public class TicketInfoActivity extends AppCompatActivity
{
    RecyclerView ticketView;

    /** Called when the activity is first created. */
    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_ticket_info);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);

        ticketView = (RecyclerView) findViewById(R.id.my_recycler_view);

        TicketAdapter adapter = new TicketAdapter(this);
        ticketView.setAdapter(adapter);
        ticketView.setHasFixedSize(true);
        ticketView.setLayoutManager(new LinearLayoutManager(this));
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item)
    {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == android.R.id.home)
        {
            // finish the activity
            onBackPressed();
            return true;
        }
        return super.onOptionsItemSelected(item);
    }
}

TicketViewHolder.java TicketViewHolder.java

package info.androidhive.navigationdrawer.activity;

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 info.androidhive.navigationdrawer.R;

public class TicketViewHolder extends RecyclerView.ViewHolder
{
    TextView textTitle,textDesc;
    ImageView imageView;
    CardView cardview;

    public TicketViewHolder(View itemView)
    {
        super(itemView);

        textTitle = (TextView) itemView.findViewById(R.id.list_title);
/*        textDesc = (TextView) itemView.findViewById(R.id.list_desc);*/
        imageView = (ImageView) itemView.findViewById(R.id.list_avatar);
        cardview = (CardView) itemView.findViewById(R.id.ticket_view);
    }
}

item_list.xml item_list.xml

<?xml version="1.0" encoding="utf-8"?>

<android.support.v7.widget.CardView
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/ticket_view"
    android:layout_width="match_parent"
    android:layout_height="160dp"
    android:layout_marginBottom="16dp"
    android:layout_marginLeft="10dp"
    android:layout_marginRight="10dp"
    android:background="#C5CAE9"
    android:foreground="?attr/selectableItemBackground"
    android:theme="@style/ThemeOverlay.AppCompat.Light">

    <RelativeLayout
        android:layout_width="match_parent"
        android:gravity="center"
        android:paddingTop="16dp"
        android:layout_height="match_parent">

        <!-- Icon -->
        <ImageView
            android:id="@+id/list_avatar"
            android:layout_width="match_parent"
            android:layout_height="85dp"
            android:scaleType="fitCenter"
            android:src="@drawable/ic_tickets_info_color_48dp"
            android:layout_alignParentTop="true"
            android:layout_alignParentRight="true"
            android:layout_alignParentEnd="true" />

        <!-- Title -->
        <TextView
            android:id="@+id/list_title"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="Product Description Goes Here... "
            android:textColor="#000000"
            android:textStyle="bold"
            android:textAppearance="?attr/textAppearanceListItem"
            android:textSize="18sp"
            android:gravity="center_horizontal"
            android:layout_below="@+id/list_avatar"
            android:layout_alignParentLeft="true"
            android:layout_alignParentStart="true"
            android:layout_marginTop="15dp"/>

        <!-- Description -->

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

activity_ticket_info.xml activity_ticket_info.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
    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:id="@+id/activity_ticket_info"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    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="info.androidhive.navigationdrawer.activity.TicketInfoActivity">

    <!--<include layout="@layout/actionbar_layout" />-->

    <android.support.v7.widget.RecyclerView
        android:id="@+id/my_recycler_view"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:clipToPadding="false"
        android:paddingBottom="16dp"
        android:paddingTop="16dp"
        android:scrollbars="vertical"
        android:layout_alignParentTop="true"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true" />
</RelativeLayout>

I think there is no such method to provide ID for each item dynamically.According to the program above you can select only a single item in the recyclerView at a time. 我认为没有这种方法可以动态地为每个项目提供ID。根据上面的程序,您一次只能在recyclerView中选择一个项目。 Better create a method in main activity as below 更好地在主要活动中创建一种方法,如下所示

public void setRVAdapterSelectedItem(String itemName){this.itemName = itemName;}

and set the clicked string to activity by calling from onClick of the adapter 并通过从适配器的onClick调用将点击的字符串设置为活动

context.setRVAdapterSelectedItem(selectedString);

So that you will get the list in Activity. 这样您就可以在“活动”中获得列表。 It is always better to use a model class for item list. 对于项目列表,最好使用模型类。 Hence you can use a boolean to identify if the item is selected or not and using that you can highlight item in onBindViewHolder 因此,您可以使用布尔值来标识是否选择了该项目,并可以使用它来突出显示onBindViewHolder中的项目

If you want to use it later as clickable, instead of assigning the id, you can set the listener for each item when they are returned and call the intent. 如果要以后用作可单击对象,而不是分配ID,则可以在返回每个项目时为每个项目设置侦听器并调用意图。

However if you still want to assign id, you can use method setId(int) which is available for all types of widgets.. and views 但是,如果仍然要分配ID,则可以使用setId(int)方法,该方法可用于所有类型的小部件..和视图

if you want to just make clickable your every cardview item you can make interface 如果您只想单击每个Cardview项目,则可以创建界面

public interface ItemClickListener {
    void onItemClick(View v, int pos);
}

and implement this on you adapter class like this 并像这样在您的适配器类上实现

public class MyAdapter extends RecyclerView.Adapter<MyAdapter.MyViewHolder>{

private List<Model> list;
Context mContext;
public MyAdapter(Context context,List<Model> list) {
    mContext=context;
    this.list = list;
}

@Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
    View itemView = LayoutInflater.from(parent.getContext())
            .inflate(R.layout.card_view, parent, false);
    return new MyViewHolder(itemView);
}

@Override
public void onBindViewHolder(MyViewHolder holder, int position) {
    final Model model = list.get(position);
    holder.name.setText("name :"+model.getName());
    holder.setItemClickListener(new ItemClickListener() {
        @Override
        public void onItemClick(View v, int position) {
            Snackbar.make(v,list.get(position).getName(),Snackbar.LENGTH_SHORT).show();
            Intent i=new Intent(mContext, Showname.class);
            mContext.startActivity(i);
        }
    });
}

@Override
public int getItemCount() {
    return list.size();
}

public class MyViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener
{
    public TextView name,branch,sem;
    ItemClickListener itemClickListener;
    public MyViewHolder(View itemView) {
        super(itemView);
        name = (TextView)itemView.findViewById(R.id.s_name);
        itemView.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        this.itemClickListener.onItemClick(v,getLayoutPosition());
    }
    public void setItemClickListener(ItemClickListener ic)
    {
        this.itemClickListener=ic;
    }
}
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM