Recyclerview维护点击的项目 - Android

时间:2016-07-13 04:00:13

标签: android xml android-recyclerview material-design

我正在使用Recyclerview。像这样

enter image description here

当用户点击一行时,特定行将以主色突出显示,但当用户拿出手指时,它会恢复透明。

但我想要的是,即使用户拿出手指,我仍希望保持最后点击的行。

个人资料列表行

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_marginBottom="10dp"
    android:focusable="true"
    android:paddingLeft="16dp"
    android:paddingRight="16dp"
    android:paddingTop="10dp"
    android:paddingBottom="10dp"
    android:clickable="true"
    android:background="@drawable/recyclerview_selector"
    android:orientation="vertical">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textAppearance="?android:attr/textAppearanceSmall"
        android:text="Small Text"
        android:id="@+id/tv_companyName"
        android:textColor="@color/colorHeaderText"
        android:layout_alignParentTop="true"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true"
        android:layout_toLeftOf="@+id/txt_bar"
        android:layout_toStartOf="@+id/txt_bar" />

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textAppearance="?android:attr/textAppearanceSmall"
        android:text="|"
        android:id="@+id/txt_bar"
        android:textColor="@color/colorHeaderBorder"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true" />

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textAppearance="?android:attr/textAppearanceSmall"
        android:text="Small Text"
        android:id="@+id/tv_helpDeskName"
        android:textColor="@color/colorHeaderText"
        android:layout_alignParentTop="true"
        android:layout_toRightOf="@+id/txt_bar"
        android:layout_alignParentRight="true"
        android:layout_alignParentEnd="true"
        android:layout_marginLeft="10dp" />
</RelativeLayout>

Recycler_view_selector

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:state_pressed="true">
        <shape>
            <solid android:color="@color/colorPrimaryDark" />
        </shape>
    </item>

    <item android:state_pressed="false">
        <shape>
            <solid android:color="@android:color/transparent" />
        </shape>
    </item>
    <item android:state_activated="true"
        android:drawable="@color/colorPrimaryDark" />
</selector>

activity_profile

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    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"
    android:background="@color/colorWhite"
    tools:context="com.example.baman.zupportdesk.CompanyProfile">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textAppearance="?android:attr/textAppearanceSmall"
        android:text="@string/company_profile"
        android:id="@+id/textView4"
        android:textColor="@color/colorBlack"
        android:textSize="16dp"
        android:layout_alignParentTop="true"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true"
        android:layout_marginLeft="10dp"
        android:layout_marginTop="5dp" />


    <LinearLayout
        android:orientation="vertical"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_marginTop="40dp"
        android:layout_alignTop="@+id/textView4"
        android:layout_alignParentLeft="true"
        android:background="@color/colorWhite"
        android:layout_alignParentStart="true"
        android:weightSum="1">

       <RelativeLayout
           android:layout_width="match_parent"
           android:layout_height="45dp"
           android:background="@drawable/recycler_view_round_corners">
           <TextView
               android:layout_width="wrap_content"
               android:layout_height="wrap_content"
               android:textAppearance="?android:attr/textAppearanceSmall"
               android:text="@string/company_name"
               android:layout_marginLeft="18dp"
               android:id="@+id/tv_companyName"
               android:textColor="@color/colorHeaderText"
               android:textStyle="bold"
               android:textSize="18dp"
               android:layout_marginTop="10dp" />

           <TextView
               android:layout_width="wrap_content"
               android:layout_height="wrap_content"
               android:textAppearance="?android:attr/textAppearanceSmall"
               android:text="|"
               android:id="@+id/txt_bar"
               android:layout_alignParentTop="true"
               android:layout_centerHorizontal="true"
               android:textSize="18dp"
               android:textColor="@color/colorHeaderBorder"
               android:layout_marginTop="10dp" />

           <TextView
               android:layout_width="wrap_content"
               android:layout_height="wrap_content"
               android:textAppearance="?android:attr/textAppearanceSmall"
               android:text="@string/help_desk_name"
               android:id="@+id/tv_helpDeskName"
               android:layout_alignParentTop="true"
               android:layout_toRightOf="@+id/txt_bar"
               android:layout_alignParentRight="true"
               android:layout_alignParentEnd="true"
               android:layout_marginLeft="10dp"
               android:textStyle="bold"
               android:textColor="@color/colorHeaderText"
               android:textSize="18dp"
               android:layout_marginTop="10dp" />
       </RelativeLayout>

        <android.support.v7.widget.RecyclerView
            android:id="@+id/recycler_view"
            android:layout_width="match_parent"
            android:layout_height="292dp"
            android:background="@drawable/recycler_view_bottom_corners"
            android:scrollbars="vertical"
            android:layout_weight="0.57" />

    </LinearLayout>

    <Button
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="@drawable/button_style"
        android:textColor="@color/colorWhite"
        android:text="@string/submit"
        android:id="@+id/button2"
        android:layout_alignParentBottom="true"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true"
        android:textStyle="bold" />

</RelativeLayout>

适配器

/**
 * Created by baman on 6/25/16.
 */

import android.graphics.Color;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.util.SparseBooleanArray;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import com.example.baman.zupportdesk.R;

import java.util.ArrayList;
import java.util.List;

public class CompanyProfileAdapter extends RecyclerView.Adapter<CompanyProfileAdapter.MyViewHolder>{
    private List<CompanyProfileData> companyProfileDataList;
    private SparseBooleanArray selectedItems;

    public class MyViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
        public TextView comName, hdName;

        public MyViewHolder(View view) {
            super(view);

            comName = (TextView) view.findViewById(R.id.tv_companyName);
            hdName = (TextView) view.findViewById(R.id.tv_helpDeskName);

            comName.setOnClickListener(this);
            hdName.setOnClickListener(this);
        }

        @Override
        public void onClick(View v) {
            int position = getAdapterPosition();
            Log.d("clicked Position", String.valueOf(position));
            Log.d("clicked company name",String.valueOf(comName.getText().toString()));
            Log.d("clicked hd name",String.valueOf(hdName.getText().toString()));
        }


    }

    public CompanyProfileAdapter(List<CompanyProfileData> companyList) {
        this.companyProfileDataList = companyList;
    }

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

    @Override
    public void onBindViewHolder(MyViewHolder holder, int position) {
        CompanyProfileData CPData = companyProfileDataList.get(position);
        holder.comName.setText(CPData.getComName());
        holder.hdName.setText(CPData.gethdName());


    }

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

Profiledata

/**
 * Created by baman on 6/25/16.
 */
public class CompanyProfileData {
    /* comName - Company Name
    *  hdName - Help Desk Name */
    private String comName, hdName;

    public CompanyProfileData(String comName, String hdName) {
        this.comName = comName;
        this.hdName = hdName;
    }

    public String getComName(){
        return comName;
    }
    public String gethdName(){
        return hdName;
    }
    public void setcomName(String name){
        this.comName = name;
    }
    public void sethdName(String hdname){
        this.hdName = hdname;
    }
}

Activity_profile

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;

import com.example.baman.zupportdesk.Data.CompanyProfileAdapter;
import com.example.baman.zupportdesk.Data.CompanyProfileData;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

public class CompanyProfile extends Activity {

    private List<CompanyProfileData> CompanyProfileList = new ArrayList<>();
    private RecyclerView recyclerView;
    private CompanyProfileAdapter mAdapter;

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

        Intent intent = getIntent();
        String company_data = intent.getStringExtra("companyData");
        Log.d("Company data", company_data);

        recyclerView = (RecyclerView) findViewById(R.id.recycler_view);
        mAdapter = new CompanyProfileAdapter(CompanyProfileList);
        RecyclerView.LayoutManager mLayoutManager = new LinearLayoutManager(getApplicationContext());
        recyclerView.setLayoutManager(mLayoutManager);
        recyclerView.setAdapter(mAdapter);

        try {
            prepareCompanyProfileData(company_data);
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    private void prepareCompanyProfileData(String company_data) throws JSONException {
        CompanyProfileData CompanyData ;
        JSONArray jsonArray = new JSONArray(company_data);
        int count = jsonArray.length();
        for(int i = 0; i< jsonArray.length();i++) {
            JSONObject jsonObject = jsonArray.getJSONObject(i);
            CompanyData = new CompanyProfileData(jsonObject.getString("CompanyName"), jsonObject.getString("CompanyName"));
            CompanyProfileList.add(CompanyData);
        }
        mAdapter.notifyDataSetChanged();
    }
}

2 个答案:

答案 0 :(得分:2)

首先在构造函数中实例化selectedItems,如下所示。

public CompanyProfileAdapter(List<CompanyProfileData> companyList) {
        this.companyProfileDataList = companyList;
        selectedItems = new SparseBooleanArray();
}

然后创建一个方法调用selectLastItem()或您喜欢的任何名称,如下所示。

public void selectLastItem(int pos){
        selectedItems.clear();
        selectedItems.put(pos, true);
        notifyDataSetChanged();
 }

然后更改你的onBindViewHolder()方法,如下所示。

 @Override
 public void onBindViewHolder(MyViewHolder holder, int position) {
        CompanyProfileData CPData = companyProfileDataList.get(position);
        holder.comName.setText(CPData.getComName());
        holder.hdName.setText(CPData.gethdName());
        holder.itemView.setBackgroundColor(selectedItems.get(position, false) ? ResourcesCompat.getColor(holder.itemView.getResources(), R.color.colorPrimary, null) : Color.TRANSPARENT);
 }

最后在onClick()中调用selectLastItem方法,如下所示。

@Override
public void onClick(View v) {
       selectLastItem(getAdapterPosition());
}

我认为这可以解决您的问题。感谢..

答案 1 :(得分:0)

在适配器的公共MyViewHolder(查看视图)中 写下这个:

 comName.setOnTouchListener(new OnTouchListener() {

                @Override
                public boolean onTouch(View v, MotionEvent event) {
                    comName.setPressed(true);
                    return true;
                }
            });