javascript

java

python

c#

android

node.js

c++

reactjs

php

html

jquery

css

.net

ios

git

ruby-on-rails

sql

c

string

ruby

android-使用ViewPager的RecyclerVi的CoordinatorLayout

我正在使用RecyclerView的视图CoordinatorLayout。我要将ViewPager附加到片段的RecyclerView吗?

在Google提供的示例中,他们仅将其附加到RecyclerView所附加的同一XML文件的CoordinatorLayout中。

有没有办法将CoordinatorLayout附加到ViewPager中片段的RecyclerView

该示例在Android开发者博客的这篇博客文章中。

trans by 2020-02-18T15:25:20Z

android-使用RecyclerVi跨越多列

因此,我要尝试的是采用交错布局,但是列表中的第一项需要跨越两列。 前两行也是固定高度。 除了第一个项目跨越两列之外,我一切正常。

我正在将RecyclerView.Adapter与StaggeredGridLayoutManager一起使用。 似乎不是开箱即用的功能。 我想我可以创建一个自定义布局管理器,但我不确定从哪里开始。 我尝试搜索,但是找不到有关如何使项目跨越多列的信息。

下图是我在列表中寻找的内容。

Staggered layout

trans by 2020-02-17T07:57:09Z

android-哪个更好? notifyDataSetChanged或notifyItemChanged在循环中?

因此,我有一个RecyclerView的活动,我想通过按活动中具有onClickListener()的按钮来更改onBindViewHolder中每个项目的onBindViewHolder

我想知道在性能方面哪个更好:

  1. 使用RecyclerView
  2. 使用条件如int i的循环小于RecyclerView,其中onBindViewHolder将被调用几次。

在这两种情况下,我都会在RecyclerView适配器中创建布尔变量,该变量由onBindViewHolder使用以了解如何更新项目。 默认情况下为假,单击按钮后为真,因此onBindViewHolder以不同的方式更新项目。

我也想知道这种方法是否完全合适。

trans by 2020-02-14T16:07:04Z

android-滚动时获取RecycleView的中心可见项

这就是我要的:

enter image description here

如上图所示,我想在Rect上画一条中心线,然后在滚动时获得中心项(以及向左或向右移动)
这是我尝试绘制水平RecycleView的方法:

    HorizontalAdapter adapter = new HorizontalAdapter(data);
    LinearLayoutManager layoutManager
            = new LinearLayoutManager(this, LinearLayoutManager.HORIZONTAL, false);
    recycleView.setLayoutManager(layoutManager);
    recycleView.setAdapter(adapter);

有什么方法可以知道哪个项目移动到2747082895838938138112的中心吗? 以及如何将RecycleView左右滚动一个位置?

更新:我试图使用滚动侦听器来获得中间位置,但是它不能用作外观。

  @Override
        public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
            super.onScrolled(recyclerView, dx, dy);
            int firstPos = layoutManager.findFirstVisibleItemPosition();
            int lastPos = layoutManager.findLastVisibleItemPosition();
            int middle = Math.abs(lastPos - firstPos) / 2 + firstPos;

            int selectedPos = -1;
            for (int i = 0; i < adapter.getItemCount(); i++) {
                if (i == middle) {
                    adapter.getItem(i).setSelected(true);
                    selectedPos = i;
                } else {
                    adapter.getItem(i).setSelected(false);
                }
            }

            adapter.notifyDataSetChanged();
        }

并得到结果:

enter image description here

我只想更改选定的项目(将文本更改为白色),当它处于蓝色Rect

trans by 2020-02-14T10:37:12Z

android-打开键盘时,Recyclerview不会滚动到结尾

我在应用程序中使用recylerview,并且每当将新元素添加到recyclerview时,它都会通过使用滚动到最后一个元素

recyclerView.scrollToPosition(adapter.getCount());

但是,每当键盘打开时(由于editTextView),它都会调整视图的大小,并且recyclerview会变小,但是无法滚动到最后一个元素。

android:windowSoftInputMode="adjustResize"

我什至尝试使用以下代码滚动到最后一个元素,但是没有用

editTextView.setOnFocusChangeListener(new View.OnFocusChangeListener() {
        @Override
        public void onFocusChange(View v, boolean hasFocus) {
            if(hasFocus){
                recyclerView.scrollToPosition(chatAdapter.getItemCount());
            }
        }
    });

我可以尝试adjustPan向上移动平移锅,但是它隐藏了我的工具栏。请提出任何纠正问题的方法。

trans by 2020-02-14T05:03:21Z

android-GridLayoutManager-如何自动适应列?

我有一个带有GridLayoutManager的RecyclerView,它显示卡片视图。 我希望这些卡根据屏幕尺寸进行重新排列(Google Play应用使用其应用卡来执行这种操作)。 这是一个例子:

enter image description here

enter image description here

这是我的应用目前的外观:

enter image description here

enter image description here

如您所见,这些卡片只是伸展而无法适应方向改变所产生的空白空间。 那我该怎么做呢?

码:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Json;
using System.Threading;
using System.Threading.Tasks;
using Android.Media;
using Android.App;
using Android.Support.V4.App;
using Android.Support.V4.Content.Res;
using Android.Support.V4.Widget;
using Android.Support.V7.Widget;
using Android.Content;
using Android.OS;
using Android.Runtime;
using Android.Util;
using Android.Views;
using Android.Widget;
using Android.Net;
using Android.Views.Animations;
using Android.Graphics;
using Android.Graphics.Drawables;
using Newtonsoft.Json;
using *******.Adapters;
using *******.Models;

namespace *******.Fragments {
    public class Dashboard : GridLayoutBase {
        private ISharedPreferences pref;
        private SessionManager session;
        private string cookie;
        private DeviceModel deviceModel;
        private RecyclerView recyclerView;
        private RecyclerView.Adapter adapter;
//      private RecyclerView.LayoutManager layoutManager;
        private GridLayoutManager gridLayoutManager;
        private List<ItemData> itemData;
        private Bitmap lastPhotoBitmap;
        private Drawable lastPhotoDrawable;
        private static Activity activity;
        private ProgressDialog progressDialog;
        private TextView noData;
        private const string URL_DASHBOARD = "http://192.168.1.101/appapi/getdashboard";
        private const string URL_DATA = "http://192.168.1.101/appapi/getdata";

        public override void OnCreate(Bundle bundle) {
            base.OnCreate(bundle);

            activity = Activity;
            session = new SessionManager();
            pref = activity.GetSharedPreferences("UserSession", FileCreationMode.Private);
            cookie = pref.GetString("PHPSESSID", string.Empty);
        }

        public async override void OnStart() {
            base.OnStart();

            progressDialog = ProgressDialog.Show(activity, String.Empty, GetString(Resource.String.loading_text));
            progressDialog.Window.ClearFlags(WindowManagerFlags.DimBehind);

            await GetDevicesInfo();

            if (deviceModel.Error == "true" && deviceModel.ErrorType == "noSensors") {
                recyclerView.Visibility = ViewStates.Gone;
                noData.Visibility = ViewStates.Visible;

                progressDialog.Hide();

                return;
            } else {
                recyclerView.Visibility = ViewStates.Visible;
                noData.Visibility = ViewStates.Gone;

                await PopulateSensorStates();
            }

//          DisplayLastPhoto();

            adapter = new ViewAdapter(itemData);

            new System.Threading.Thread(new System.Threading.ThreadStart(() => {
                activity.RunOnUiThread(() => {
                    recyclerView.SetAdapter(adapter);
                });
            })).Start();

            progressDialog.Hide();
        }

        public async Task GetDevicesInfo() {
            var jsonFetcher = new JsonFetcher();
            JsonValue jsonDashboard = await jsonFetcher.FetchDataWithCookieAsync(URL_DASHBOARD, cookie);
            deviceModel = new DeviceModel();
            deviceModel = JsonConvert.DeserializeObject<DeviceModel>(jsonDashboard);
        }

        // Shows sensor states
        public async Task PopulateSensorStates() {
            itemData = new List<ItemData>();
            string lastValue = String.Empty;

            foreach (var sensor in this.deviceModel.Sensors) {
                var sensorImage = ResourcesCompat.GetDrawable(Resources, Resource.Drawable.smoke_red, null);

                switch (sensor.Type) {
                case "2":
                    var jsonFetcher = new JsonFetcher();
                    JsonValue jsonData = await jsonFetcher.FetchSensorDataAsync(URL_DATA, sensor.Id, "DESC", "1", cookie);
                    var deviceModel = new DeviceModel();
                    deviceModel = JsonConvert.DeserializeObject<DeviceModel>(jsonData);
                    lastValue = deviceModel.SensorData.Last().Value;
                    break;
                case "4":
                    await RenderLastCameraPhoto();
                    sensorImage = new BitmapDrawable(Resources, lastPhotoBitmap);
                    break;
                }

                itemData.Add(new ItemData() {
                    id = sensor.Id,
                    value = lastValue,
                    type = sensor.Type,
                    image = sensorImage,
                    title = sensor.Name.First().ToString().ToUpper() + sensor.Name.Substring(1).ToLower(),
                });
            }
        }

        // Shows the last camera photo
        public async Task RenderLastCameraPhoto() {
            if (deviceModel.Error == "true" && deviceModel.ErrorType == "noPhoto") {
                //TODO: Show a "No photo" picture
            } else {
                string url = deviceModel.LastPhotoLink;
                lastPhotoBitmap = await new ImageDownloader().GetImageBitmapFromUrlAsync(url, activity, 300, 300);
            }
        }

        public async void UpdateData(bool isSwipeRefresh) {
            await GetDevicesInfo();

            if (deviceModel.Error == "true" && deviceModel.ErrorType == "noSensors") {
                recyclerView.Visibility = ViewStates.Gone;
                noData.Visibility = ViewStates.Visible;

                return;
                } else {
                recyclerView.Visibility = ViewStates.Visible;
                noData.Visibility = ViewStates.Gone;

                await PopulateSensorStates();
            }

            adapter = new ViewAdapter(itemData);

            new System.Threading.Thread(new System.Threading.ThreadStart(() => {
                activity.RunOnUiThread(() => {
                    recyclerView.SetAdapter(adapter);
                });
            })).Start();

            adapter.NotifyDataSetChanged();
        }

        public override View OnCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
            View view = inflater.Inflate(Resource.Layout.Dashboard, container, false);
            noData = view.FindViewById<TextView>(Resource.Id.no_data_title);

            SwipeRefreshLayout swipeRefreshLayout = view.FindViewById<SwipeRefreshLayout>(Resource.Id.swipe_container);
            //          swipeRefreshLayout.SetColorSchemeResources(Color.LightBlue, Color.LightGreen, Color.Orange, Color.Red);

            // On refresh button press/swipe, updates the recycler view with new data
            swipeRefreshLayout.Refresh += (sender, e) => {
                UpdateData(true);

                swipeRefreshLayout.Refreshing = false;
            };

            var gridLayoutManager = new GridLayoutManager(activity, 2);

            recyclerView = view.FindViewById<RecyclerView>(Resource.Id.dashboard_recycler_view);
            recyclerView.HasFixedSize = true;
            recyclerView.SetLayoutManager(gridLayoutManager);
            recyclerView.SetItemAnimator(new DefaultItemAnimator());
            recyclerView.AddItemDecoration(new SpaceItemDecoration(15));

            return view;
        }

        public class ViewAdapter : RecyclerView.Adapter {
            private List<ItemData> itemData;
            public string sensorId;
            public string sensorType;
            private ImageView imageId;
            private TextView sensorValue;
            private TextView sensorTitle;

            public ViewAdapter(List<ItemData> itemData) {
                this.itemData = itemData;
            }

            public class ItemView : RecyclerView.ViewHolder {
                public View mainView { get; set; }

                public string id { get; set; }

                public string type { get; set; }

                public ImageView image { get; set; }

                //              public TextView value { get; set; }

                public TextView title { get; set; }

                public ItemView(View view) : base(view) {
                    mainView = view;
                }
            }

            public override RecyclerView.ViewHolder OnCreateViewHolder(ViewGroup parent, int viewType) {
                View itemLayoutView = LayoutInflater.From(parent.Context).Inflate(Resource.Layout.DashboardItems, null);
                CardView cardView = itemLayoutView.FindViewById<CardView>(Resource.Id.dashboard_card_view);
                imageId = itemLayoutView.FindViewById<ImageView>(Resource.Id.sensor_image);
//              sensorValue = itemLayoutView.FindViewById<TextView>(Resource.Id.sensor_value);
                sensorTitle = itemLayoutView.FindViewById<TextView>(Resource.Id.sensor_title);

                var viewHolder = new ItemView(itemLayoutView) {
                    id = sensorId,
                    type = sensorType,
                    image = imageId,
//                  value = sensorValue,
                    title = sensorTitle
                };

                return viewHolder;
            }

            public override void OnBindViewHolder(RecyclerView.ViewHolder viewHolder, int position) {
                ItemView itemHolder = viewHolder as ItemView;

                itemHolder.image.SetImageDrawable(itemData[position].image);

                if (itemData[position].type == "2") { // Temperature
                    itemHolder.title.Text = itemData[position].title + ": " + itemData[position].value;
                } else {
                    itemHolder.title.Text = itemData[position].title;
                }

                var bundle = new Bundle();
                var dualColumnList = new DualColumnList();
                var gallery = new Gallery();

                EventHandler clickUpdateViewEvent = ((sender, e) => {
                    bundle.PutString("id", itemData[position].id);
                    gallery.Arguments = bundle;
                    dualColumnList.Arguments = bundle;

                    if (itemData[position].type == "4") { // Camera
                        ((FragmentActivity)activity).ShowFragment(gallery, itemData[position].title, itemData[position].type, true);
                    } else {
                        ((FragmentActivity)activity).ShowFragment(dualColumnList, itemData[position].title, itemData[position].type, true);
                    }
                });

                itemHolder.image.Click += clickUpdateViewEvent;
//              itemHolder.value.Click += clickUpdateViewEvent;
                itemHolder.title.Click += clickUpdateViewEvent;
            }

            public override int ItemCount {
                get { return itemData.Count; }
            }
        }

        public class ItemData {
            public string id { get; set; }

            public string type { get; set; }

            public Drawable image { get; set; }

            public string value { get; set; }

            public string title { get; set; }
        }
    }
}

片段布局:

<?xml version="1.0" encoding="utf-8"?>
<android.support.v4.widget.SwipeRefreshLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/swipe_container"
    android:layout_width="match_parent"
    android:layout_height="match_parent">
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:gravity="center_horizontal"
        android:weightSum="1">
        <RelativeLayout
            android:layout_width="0dp"
            android:layout_height="match_parent"
            android:layout_weight="0.9"
            android:scrollbars="vertical">
            <android.support.v7.widget.RecyclerView
                android:id="@+id/dashboard_recycler_view"
                android:layout_width="match_parent"
                android:layout_height="match_parent" />
            <TextView
                android:text="@string/no_data_text"
                android:id="@+id/no_data_title"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:textSize="30sp"
                android:gravity="center"
                android:layout_centerInParent="true" />
        </RelativeLayout>
    </LinearLayout>
</android.support.v4.widget.SwipeRefreshLayout>

片段项目布局:

<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/dashboard_card_view"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content">
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:gravity="center_horizontal"
        android:orientation="vertical"
        android:foreground="?android:attr/selectableItemBackground">
        <ImageView
            android:id="@+id/sensor_image"
            android:layout_width="120dp"
            android:layout_height="120dp"
            android:paddingTop="5dp"
            android:layout_alignParentTop="true" />
    <!--        <TextView
            android:id="@+id/sensor_value"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textSize="30sp"
            android:layout_below="@id/sensor_image"
            android:gravity="center" />-->
        <TextView
            android:id="@+id/sensor_title"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:textSize="23sp"
            android:layout_below="@id/sensor_image"
            android:gravity="center"
            android:layout_alignParentBottom="true" />
    </LinearLayout>
</android.support.v7.widget.CardView>
trans by 2020-02-11T06:55:48Z

android-如何突出显示回收器视图的选定项目?

我有一个回收站视图,其中包含从内部存储器加载的图像。我想在单击时突出显示选定的项目。我尝试了很多东西,但是没有用。实际上,我需要的是,当我在Recycler View中单击任何项时,该项必须位于我的ArrayList中,并且该项也应突出显示,并且当我单击或说取消选择时,该项必须再次变为正常。这是我的代码:

public class Images extends Fragment {
    private List<ImageHolder> imageList;
    Cursor imageCursor;

    RecyclerView recyclerView;
    MyImageAdapter adapter;
    ActionButton clickButton;
    List<String> listofImages;
    List<Integer> pos;
    int columnIndex;
    StringBuilder stringBuilder;
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,   Bundle savedInstanceState) {
        View rootlayout = inflater.inflate(R.layout.image, container, false);
        listofImages=new ArrayList<String>();
        pos=new ArrayList<Integer>();
        stringBuilder=new StringBuilder();
        ContentResolver imageResolver = getActivity().getContentResolver();
        Uri imageUri = android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
        String projection[]={MediaStore.Images.Thumbnails._ID,MediaStore.Images.Media.TITLE};
        imageCursor = getActivity().managedQuery(imageUri, projection, null, null, null);

        clickButton= (ActionButton) rootlayout.findViewById(R.id.action_button);

        recyclerView = (RecyclerView) rootlayout.findViewById(R.id.recycler_view_image);
        adapter = new MyImageAdapter(getActivity(), getImageList());

        recyclerView.setAdapter(adapter);
        recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));

        recyclerView.addOnItemTouchListener(new RecyclerTouchListener(getActivity(),recyclerView,new RecyclerTouchListener.ClickListener() {
            @Override
            public void onClick(View view, int position) {
               TextView tv= (TextView) view.findViewById(R.id.list_text_all);
                    int flag=0;

                    String[] projection = {MediaStore.Images.Media.DATA};
                    imageCursor = getActivity().managedQuery(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
                            projection, 
                            null,       
                            null,
                            null);
                    columnIndex = imageCursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
                    imageCursor.moveToPosition(position);
                    // Get image filename
                    String imagePath = imageCursor.getString(columnIndex);
                    if (listofImages.contains(imagePath)){
                        Log.d("Contains Test","Yes");
                        listofImages.remove(imagePath);
                        pos.remove(position);
                    } else {
                        listofImages.add(imagePath);
                        pos.add(position);
                        Log.d("Contains Test","No");
                    }

                String s=listofImages.size()+" "+imagePath;
                Log.d("Inserted",s);
            }

            @Override
            public void onLongClick(View view, int position) {}
        }));

        clickButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                for (int i=0;i<listofImages.size();i++){
                    stringBuilder.append(listofImages.get(i)+"\n");
                }
                Toast.makeText(getActivity(),stringBuilder,Toast.LENGTH_LONG).show();
            }
        });

        return rootlayout;
    }

    public List<ImageHolder> getImageList() {
        imageList=new ArrayList<ImageHolder>();

        if(imageCursor!=null && imageCursor.moveToFirst()){

           int titleColumn = imageCursor.getColumnIndex
                    (android.provider.MediaStore.Images.Media.TITLE);
            int idColumn = imageCursor.getColumnIndex
                    (android.provider.MediaStore.Images.Media._ID);

            do {
                ImageHolder img=new ImageHolder();
                img.id=imageCursor.getLong(idColumn);
                img.title=imageCursor.getString(titleColumn);

                img.iconid= imageCursor.getInt(idColumn);


                imageList.add(img);
            }
            while (imageCursor.moveToNext());
        }

        return  imageList;
    }
}

这是我的适配器类:

public class MyImageAdapter extends RecyclerView.Adapter<MyImageAdapter.MyViewHolder> {
    Context context;
    private LayoutInflater inflater;
    List<ImageHolder> data= Collections.emptyList();
    private ClickListener clickListener;
    int width,height;

    public MyImageAdapter(Context context, List<ImageHolder> data1) {
        inflater = LayoutInflater.from(context);
        this.data=data1;
        this.context=context;
    }

    @Override
    public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View view = inflater.inflate(R.layout.all_row, parent, false);
        MyViewHolder holder=new MyViewHolder(view);
        return holder;
    }

    @Override
    public void onBindViewHolder(MyViewHolder holder, int position) {
        try{
            ImageHolder current=data.get(position);
            holder.title.setText(current.title);

            Log.d("Imageid:"+current.iconid,"");
            Uri IMAGE_URI = Uri.withAppendedPath(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "" + current.iconid);

            Bitmap bitmap = Bitmap.createScaledBitmap(decodeUri(IMAGE_URI), 200, 200, true);
            holder.img.setImageBitmap(bitmap);
        }
        catch(Exception e){}
    }
    public void deleteRecyclerData(int position){
        data.remove(position);
        notifyItemRemoved(position);
    }


    private Bitmap decodeUri(Uri selectedImage) throws FileNotFoundException {
        BitmapFactory.Options o = new BitmapFactory.Options();
        o.inJustDecodeBounds = true;
        BitmapFactory.decodeStream(
               context.getContentResolver().openInputStream(selectedImage), null, o);

        final int REQUIRED_SIZE = 100;

        int width_tmp = o.outWidth, height_tmp = o.outHeight;
        int scale = 1;
        while (true) {
            if (width_tmp / 2 < REQUIRED_SIZE || height_tmp / 2 < REQUIRED_SIZE) {
                break;
            }
            width_tmp /= 2;
            height_tmp /= 2;
            scale *= 2;
        }

        BitmapFactory.Options o2 = new BitmapFactory.Options();
        o2.inSampleSize = scale;
        return BitmapFactory.decodeStream(
                context.getContentResolver().openInputStream(selectedImage), null, o2);
    }
    @Override
    public int getItemCount() {
        return data.size();
    }

    public class MyViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener{
        TextView title;
      // TextView artist;
        ImageView img;
        CheckBox checkBox;

        public MyViewHolder(View itemView) {
            super(itemView);
            title= (TextView) itemView.findViewById(R.id.list_text_all);
            img= (ImageView) itemView.findViewById(R.id.list_image_all);
            img.setOnClickListener(this);
        }

        @Override
        public void onClick(View v) {}
    }
    public interface ClickListener{
        public void itemClicked(View view, int position);
    }
}
trans by 2020-02-09T06:00:55Z

android-notifyDataSetChanged在RecyclerVi上不起作用

我从服务器获取数据,然后解析它并将其存储在列表中。 我将此列表用于RecyclerView的适配器。 我正在使用片段。

我将Nexus 5与KitKat结合使用。 我正在为此使用支持库。 这会有所作为吗?

这是我的代码:(使用虚拟数据作为问题)

成员变量:

List<Business> mBusinesses = new ArrayList<Business>();

RecyclerView recyclerView;
RecyclerView.LayoutManager mLayoutManager;
BusinessAdapter mBusinessAdapter;

我的onCreateView()

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
        Bundle savedInstanceState) {

    // Getting data from server
    getBusinessesDataFromServer();

    View view = inflater.inflate(R.layout.fragment_business_list,
            container, false);
    recyclerView = (RecyclerView) view
            .findViewById(R.id.business_recycler_view);
    recyclerView.setHasFixedSize(true);

    mLayoutManager = new LinearLayoutManager(getActivity());
    recyclerView.setLayoutManager(mLayoutManager);

    mBusinessAdapter = new BusinessAdapter(mBusinesses);
    recyclerView.setAdapter(mBusinessAdapter);

    return view;
}

从服务器获取数据后,将调用getItemCount()

protected void parseResponse(JSONArray response, String url) {
    // insert dummy data for demo

    mBusinesses.clear();

    Business business;

    business = new Business();
    business.setName("Google");
    business.setDescription("Google HeadQuaters");
    mBusinesses.add(business);

    business = new Business();
    business.setName("Yahoo");
    business.setDescription("Yahoo HeadQuaters");
    mBusinesses.add(business);

    business = new Business();
    business.setName("Microsoft");
    business.setDescription("Microsoft HeadQuaters");
    mBusinesses.add(business);

    Log.d(Const.DEBUG, "Dummy Data Inserted\nBusinesses Length: "
            + mBusinesses.size());

    mBusinessAdapter = new BusinessAdapter(mBusinesses);
    mBusinessAdapter.notifyDataSetChanged();
}

我的BusinessAdapter:

public class BusinessAdapter extends
    RecyclerView.Adapter<BusinessAdapter.ViewHolder> {

    private List<Business> mBusinesses = new ArrayList<Business>();

    // Provide a reference to the type of views that you are using
    // (custom viewholder)
    public static class ViewHolder extends RecyclerView.ViewHolder {
        public TextView mTextViewName;
        public TextView mTextViewDescription;
        public ImageView mImageViewLogo;

        public ViewHolder(View v) {
            super(v);
            mTextViewName = (TextView) v
                    .findViewById(R.id.textView_company_name);
            mTextViewDescription = (TextView) v
                    .findViewById(R.id.textView_company_description);
            mImageViewLogo = (ImageView) v
                    .findViewById(R.id.imageView_company_logo);
        }
    }

    // Provide a suitable constructor (depends on the kind of dataset)
    public BusinessAdapter(List<Business> myBusinesses) {

        Log.d(Const.DEBUG, "BusinessAdapter -> constructor");

        mBusinesses = myBusinesses;
    }

    // Create new views (invoked by the layout manager)
    @Override
    public BusinessAdapter.ViewHolder onCreateViewHolder(ViewGroup parent,
            int viewType) {

        Log.d(Const.DEBUG, "BusinessAdapter -> onCreateViewHolder()");

        // create a new view
        View v = LayoutInflater.from(parent.getContext()).inflate(
                R.layout.item_business_list, parent, false);

        ViewHolder vh = new ViewHolder(v);
        return vh;
    }

    // Replace the contents of a view (invoked by the layout manager)
    @Override
    public void onBindViewHolder(ViewHolder holder, int position) {
        // - get element from your dataset at this position
        // - replace the contents of the view with that element

        Log.d(Const.DEBUG, "BusinessAdapter -> onBindViewHolder()");

        Business item = mBusinesses.get(position);
        holder.mTextViewName.setText(item.getName());
        holder.mTextViewDescription.setText(item.getDescription());
        holder.mImageViewLogo.setImageResource(R.drawable.ic_launcher);

    }

    // Return the size of your dataset (invoked by the layout manager)
    @Override
    public int getItemCount() {

        Log.d(Const.DEBUG, "BusinessAdapter -> getItemCount()");

        if (mBusinesses != null) {
            Log.d(Const.DEBUG, "mBusinesses Count: " + mBusinesses.size());
            return mBusinesses.size();
        }
        return 0;
    }
}

但是我没有在视图中显示数据。 我究竟做错了什么?

这是我的日志,

07-14 21:15:35.669: D/xxx(2259): Dummy Data Inserted
07-14 21:15:35.669: D/xxx(2259): Businesses Length: 3
07-14 21:26:26.969: D/xxx(2732): BusinessAdapter -> constructor

在此之后,我没有任何日志。 适配器中的getItemCount()是否应该再次调用?

trans by 2020-02-06T11:49:36Z

Java-Recyclerview极慢地从毕加索加载缓存的图像

我实现了一个RecyclerView,其中主要包含通过Picasso加载的图像。 我的问题是,当我向下或向上滚动视图时,占位符图像会出现大约20分钟。 一秒钟,然后将其替换为实际图像。 它滚动非常平稳,但实际上不可用。 每当屏幕上滚动滚动时都会发生这种情况。

毕加索显然正在将图像缓存到磁盘上,因为它们的加载速度比初始加载时间快,但是它们肯定会立即从缓存中重新加载。 我执行不正确的是什么?

我的适配器代码:

public class ExploreAdapter extends RecyclerView.Adapter<ExploreAdapter.ExploreViewHolder> {

    private List<ExploreItem> exploreItemList;
    private Context mContext;
    private int deviceWidth = PrefUtils.getDeviceWidth();

    public ExploreAdapter(Context context, List<ExploreItem> exploreItemList){
        this.mContext = context;
        this.exploreItemList = exploreItemList;
    }

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

    @Override
    public void onBindViewHolder(ExploreViewHolder exploreViewHolder, int i){
        ExploreItem item = exploreItemList.get(i);
        exploreViewHolder.getvTitle().setText(item.getTitle());
        exploreViewHolder.getvUsername().setText(item.getUsername());
        exploreViewHolder.getvNumLikes().setText(item.getNbOfLikes());

        Picasso.with(mContext).load(item.getMediaLocation().trim())
                .resize(deviceWidth, deviceWidth)
                .centerCrop()
                .placeholder(R.drawable.profile_background)
                .into(exploreViewHolder.getvImage());

        Picasso.with(mContext).load(item.getUserProfilePicUrl().trim())
                .placeholder(R.drawable.profile_picture)
                .into(exploreViewHolder.getvProfilePic());
    }

    @Override
    public ExploreViewHolder onCreateViewHolder(ViewGroup viewGroup, int i){
        View itemView = LayoutInflater.
                from(viewGroup.getContext()).
                inflate(R.layout.explore_item, viewGroup, false);

        return new ExploreViewHolder(itemView);
    }

    public static class ExploreViewHolder extends RecyclerView.ViewHolder{
        private TextView  vTitle,
                          vUsername,
                          vNumLikes;

        private SquareImage vImage;
        private ImageView vProfilePic;

        public ExploreViewHolder(View v){
            super(v);
            this.vTitle = (TextView) v.findViewById(R.id.explore_item_title);
            this.vUsername = (TextView) v.findViewById(R.id.explore_item_username);
            this.vNumLikes = (TextView) v.findViewById(R.id.explore_item_number_likes);
            this.vImage = (SquareImage) v.findViewById(R.id.explore_item_image);
            this.vProfilePic = (ImageView) v.findViewById(R.id.explore_item_profile_picture);
        }

        public TextView getvTitle() {
            return vTitle;
        }

        public TextView getvUsername() {
            return vUsername;
        }

        public ImageView getvProfilePic() {
            return vProfilePic;
        }

        public SquareImage getvImage() {
            return vImage;
        }

        public TextView getvNumLikes() {
            return vNumLikes;
        }

        public void setvImage(SquareImage vImage) {
            this.vImage = vImage;
        }

        public void setvNumLikes(TextView vNumLikes) {
            this.vNumLikes = vNumLikes;
        }

        public void setvProfilePic(ImageView vProfilePic) {
            this.vProfilePic = vProfilePic;
        }

        public void setvTitle(TextView vTitle) {
            this.vTitle = vTitle;
        }

        public void setvUsername(TextView vUsername) {
            this.vUsername = vUsername;
        }
    }
}

任何帮助表示赞赏。

trans by 2020-02-03T02:07:34Z

android-如何在RecyclerView中实现多选?

This is implemented using ListView

ListView具有多选模式,如何使用RecyclerView实现相同的选择? 如何处理onItemCheckedStateChanged?我检查了这个但是我不能从中看出很多。 任何代码片段或实现相同代码的示例项目都将是不错的选择。 提前致谢。

trans by 2020-01-26T01:36:55Z

android-RecyclerView标头和

也许以前有人问过这个问题,但我似乎找不到确切的答案或解决方案。 我开始使用RecyclerView,并使用LinearLayoutManager实施了它。 现在,我想添加自定义的页眉和页脚项目,这些项目与RecyclerView中的其余项目不同。 页眉和页脚不应发粘,我希望它们与其余项目一起滚动。 可以有人指出如何做到这一点或只是分享想法的例子。 我会非常感激。 谢谢

trans by 2020-01-22T07:46:56Z

Android:控制平滑滚动浏览回收站vi

我在CardView中使用Recyclerview。 我知道如何控制列表视图的速度。 但不是针对Recyclerview。

我在找到的类名称SmoothScroll中进行了大量搜索。 如何使用? 我不知道! 现在,默认情况下,Recyclerview的滚动速度很快。

更新:

我总结了吉尔答案

trans by 2020-01-18T03:19:05Z

滚动-Android:如何获取RecyclerView的当前X偏移量?

我将onScrolled用于无限的“时间选择器轮播”,发现这不是最佳方法(最后一个问题)

现在,我找到了RecyclerView,但是我无法获得RecyclerView在X方向上的当前滚动偏移量? (假设每个项目的宽度均为100px,第二个项目的可见度仅为50%,因此滚动偏移为150px)

  • 所有项目都具有相同的宽度,但是在第一个项目之前,最后一个项目之后有一些间隙
  • onScrolled返回findFirstVisibleItemPosition(文档说:初始滚动值)
  • onScrolled具有findFirstVisibleItemPosition,但是我无法使用

更新

我只是找到了一种跟踪X位置,同时使用onScrolled回调更新值的方法,但是我宁愿获取实际值,而不是一直跟踪它!

private int overallXScroll = 0;
//...
mRecyclerView.setOnScrollListener(new RecyclerView.OnScrollListener() {
        @Override
        public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
            super.onScrolled(recyclerView, dx, dy);

            overallXScroll = overallXScroll + dx;

            Log.i("check","overallXScroll->" + overallXScroll);

        }
    });
trans by 2020-01-15T12:25:25Z

android recyclerview-回收者视图:检测到不一致。 无效的视图支架适配器positionViewHold

Recycler View Inconsistency检测到错误,快速滚动时或加载更多项目时滚动。

FATAL EXCEPTION: main
Process: com.pratap.endlessrecyclerview, PID: 21997
java.lang.IndexOutOfBoundsException: Inconsistency detected. Invalid view holder adapter positionViewHolder{56a082c position=40 id=-1, oldPos=39, pLpos:39 scrap [attachedScrap] tmpDetached no parent}
at android.support.v7.widget.RecyclerView$Recycler.validateViewHolderForOffsetPosition(RecyclerView.java:4251)
at android.support.v7.widget.RecyclerView$Recycler.getViewForPosition(RecyclerView.java:4382)
at android.support.v7.widget.RecyclerView$Recycler.getViewForPosition(RecyclerView.java:4363)
at android.support.v7.widget.LinearLayoutManager$LayoutState.next(LinearLayoutManager.java:1961)
at android.support.v7.widget.LinearLayoutManager.layoutChunk(LinearLayoutManager.java:1370)
at android.support.v7.widget.LinearLayoutManager.fill(LinearLayoutManager.java:1333)
at android.support.v7.widget.LinearLayoutManager.onLayoutChildren(LinearLayoutManager.java:562)
at android.support.v7.widget.RecyclerView.dispatchLayout(RecyclerView.java:2864)
at android.support.v7.widget.RecyclerView.consumePendingUpdateOperations(RecyclerView.java:1445)
at android.support.v7.widget.RecyclerView.access$400(RecyclerView.java:144)
at android.support.v7.widget.RecyclerView$1.run(RecyclerView.java:282)
at android.view.Choreographer$CallbackRecord.run(Choreographer.java:858)
at android.view.Choreographer.doCallbacks(Choreographer.java:670)
at android.view.Choreographer.doFrame(Choreographer.java:603)
at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:844)
at android.os.Handler.handleCallback(Handler.java:746)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5443)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:728)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:618)

适配器

public class DataAdapter extends RecyclerView.Adapter {
    private final int VIEW_ITEM = 1;
    private final int VIEW_PROG = 0;

    private List<Feed> mFeed;
    // The minimum amount of items to have below your current scroll position
    // before loading more.
    private int visibleThreshold = 5;
    private int lastVisibleItem, totalItemCount;
    private boolean loading;
    private OnLoadMoreListener onLoadMoreListener;

    public DataAdapter(List<Feed> feeds, RecyclerView recyclerView) {

        mFeed = feeds;

        if (recyclerView.getLayoutManager() instanceof LinearLayoutManager) {

            final LinearLayoutManager linearLayoutManager = (LinearLayoutManager) recyclerView
                .getLayoutManager();

            recyclerView
                .addOnScrollListener(new RecyclerView.OnScrollListener() {
                    @Override
                    public void onScrolled(RecyclerView recyclerView,
                        int dx, int dy) {
                        super.onScrolled(recyclerView, dx, dy);

                        totalItemCount = linearLayoutManager.getItemCount();
                        lastVisibleItem = linearLayoutManager
                            .findLastVisibleItemPosition();
                        if (!loading
                            && totalItemCount <= (lastVisibleItem + visibleThreshold)) {
                            // End has been reached
                            // Do something
                            if (onLoadMoreListener != null) {
                                onLoadMoreListener.onLoadMore();
                            }
                            loading = true;
                        }
                    }
                });
        }
    }

    @Override
    public int getItemViewType(int position) {
        return mFeed.get(position) == null ? VIEW_PROG : VIEW_ITEM;
    }

    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent,
        int viewType) {
        RecyclerView.ViewHolder vh;
        if (viewType == VIEW_ITEM) {
            View v = LayoutInflater.from(parent.getContext()).inflate(
                R.layout.list_row, parent, false);

            vh = new StudentViewHolder(v);
        }
        else {
            View v = LayoutInflater.from(parent.getContext()).inflate(
                R.layout.progress_item, parent, false);

            vh = new ProgressViewHolder(v);
        }
        return vh;
    }

    @Override
    public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
        if (holder instanceof StudentViewHolder) {

            Feed singleStudent= (Feed) mFeed.get(position);
            ((StudentViewHolder) holder).tvName.setText(singleStudent.getTitle());
            ((StudentViewHolder) holder).student= singleStudent;
        } else {
            ProgressViewHolder.PROGRESS_BAR.setIndeterminate(true);
        }
    }

    public void setLoaded() {
        loading = false;
    }

    public void  addFeed(Feed feed) {
        mFeed.add(feed);
        //mFeed.addAll(0, (Collection<? extends Feed>) feed);
        notifyItemInserted(mFeed.size());
        //notifyItemRangeInserted(0,mFeed.size());
        notifyDataSetChanged();
        //notifyItemInserted(mFeed.size());
        //setLoaded();
        //notifyItemInserted(mFeed.size());
    }

    public void removeAll(){
        mFeed.clear();
        notifyDataSetChanged();
    }

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

    public void setOnLoadMoreListener(OnLoadMoreListener onLoadMoreListener) {
        this.onLoadMoreListener = onLoadMoreListener;
    }

    public static class StudentViewHolder extends RecyclerView.ViewHolder {
        public TextView tvName;

        public Feed student;
        public StudentViewHolder(View v) {
            super(v);
            tvName = (TextView) v.findViewById(R.id.tvName);

            //tvEmailId = (TextView) v.findViewById(R.id.tvEmailId);
        }
    }

    public static class ProgressViewHolder extends RecyclerView.ViewHolder {
        //public ProgressBar progressBar;
        public static ProgressBar PROGRESS_BAR;
        public ProgressViewHolder(View v) {
            super(v);
            PROGRESS_BAR = (ProgressBar) v.findViewById(R.id.progressBar1);
            //  progressBar = (ProgressBar) v.findViewById(R.id.progressBar1);
        }
    }
}

活动

public class MainActivity extends AppCompatActivity implements SwipeRefreshLayout.OnRefreshListener {

    private Toolbar toolbar;

    private TextView tvEmptyView;
    private RecyclerView mRecyclerView;
    private DataAdapter mAdapter;
    private LinearLayoutManager mLayoutManager;
    private RestManager mManager;
    private List<Feed> mFeed;
    SwipeRefreshLayout mSwipeRefreshLayout;
    protected Handler handler;
    private int currentPage=1;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        toolbar = (Toolbar) findViewById(R.id.toolbar);
        tvEmptyView = (TextView) findViewById(R.id.empty_view);
        mRecyclerView = (RecyclerView) findViewById(R.id.my_recycler_view);
        mSwipeRefreshLayout= (SwipeRefreshLayout) findViewById(R.id.swipe_refresh_layout);
        mSwipeRefreshLayout.setOnRefreshListener(this);
        //studentList = new ArrayList<Student>();
        mFeed = new ArrayList<Feed>();
        handler = new Handler();
        if (toolbar != null) {
            setSupportActionBar(toolbar);
            getSupportActionBar().setTitle("Android Students");

        }
        mManager = new RestManager();

        // use this setting to improve performance if you know that changes
        // in content do not change the layout size of the RecyclerView
        mRecyclerView.setHasFixedSize(true);

        mLayoutManager = new LinearLayoutManager(this);

        // use a linear layout manager
        mRecyclerView.setLayoutManager(mLayoutManager);

        // create an Object for Adapter
        mAdapter = new DataAdapter(mFeed,mRecyclerView);

        // set the adapter object to the Recyclerview
        mRecyclerView.setAdapter(mAdapter);
        //   mAdapter.notifyDataSetChanged();

        loadData(false);

        //        if (mFeed.isEmpty()) {
        //            mRecyclerView.setVisibility(View.GONE);
        //            tvEmptyView.setVisibility(View.VISIBLE);
        //
        //        } else {
        //            mRecyclerView.setVisibility(View.VISIBLE);
        //            tvEmptyView.setVisibility(View.GONE);
        //        }

        mAdapter.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore() {
                //add null , so the adapter will check view_type and show progress bar at bottom
                mFeed.add(null);
                mAdapter.notifyItemInserted(mFeed.size() - 1);

                handler.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        //   remove progress item
                        mFeed.remove(mFeed.size() - 1);
                        // mAdapter.notifyItemRemoved(mFeed.size());
                        //add items one by one
                        int start = mFeed.size();
                        currentPage++;

                        Log.d("CurrentPage", String.valueOf(currentPage));
                        Call<Results> listCall = mManager.getFeedApi().getAllFeeds(1);

                        listCall.enqueue(new Callback<Results>() {

                            @Override
                            public void onResponse(Call<Results> call, Response<Results> response) {
                                mSwipeRefreshLayout.setRefreshing(false);
                                if (response.isSuccess()) {
                                    if (response.body() != null) {
                                        Results feedList = response.body();

                                        // List<Results> newUsers = response.body();

                                        Log.d("Retrofut", String.valueOf(feedList));

                                        for (int i = 0; i < feedList.results.size(); i++) {
                                            Feed feed = feedList.results.get(i);
                                            // mFeed.add(feed);
                                            mAdapter.addFeed(feed);
                                            //                                        mAdapter.notifyDataSetChanged();


                                            //mAdapter.notifyItemInserted(mFeed.size());

                                        }
                                        //    mAdapter.notifyDataSetChanged();
                                    }
                                }
                            }

                            @Override
                            public void onFailure(Call<Results> call, Throwable t) {
                                Log.d("Retrofut", "Error");
                                mFeed.remove(mFeed.size() - 1);
                                mAdapter.notifyItemRemoved(mFeed.size());

                                mAdapter.setLoaded();
                                mSwipeRefreshLayout.setRefreshing(false);
                            }
                        });

                        //        for (int i = 1; i <= 20; i++) {
                        //            studentList.add(new Student("Student " + i, "androidstudent" + i + "@gmail.com"));
                        //
                        //        }

                        mAdapter.setLoaded();
                        //or you can add all at once but do not forget to call mAdapter.notifyDataSetChanged();

                    }
                }, 2000);
            }
        });
    }

    // load initial data
    private void loadData(final boolean removePreData) {

        Call<Results> listCall = mManager.getFeedApi().getAllFeeds(1);

        listCall.enqueue(new Callback<Results>() {

                             @Override
                             public void onResponse(Call<Results> call, Response<Results> response) {

                                 if (response.isSuccess()) {
                                     if (response.body() != null) {
                                         //  if(removePreData) mAdapter.removeAll();
                                         Results feedList = response.body();
                                         Log.d("Retrofut", String.valueOf(feedList));

                                         for (int i = 0; i < feedList.results.size(); i++) {
                                             Feed feed = feedList.results.get(i);
                                             // mFeed.add(feed);
                                             //mAdapter.notifyDataSetChanged();
                                             mAdapter.addFeed(feed);
                                         }

                                         mSwipeRefreshLayout.setRefreshing(false);
                                     }
                                 }
                             }

                             @Override
                             public void onFailure(Call<Results> call, Throwable t) {
                                 Log.d("Retrofut", String.valueOf(t));
                                 mFeed.remove(mFeed.size() - 1);
                                 mAdapter.notifyItemRemoved(mFeed.size());
                                 mAdapter.setLoaded();
                                 mSwipeRefreshLayout.setRefreshing(false);
                             }
                         }
        );

        //        for (int i = 1; i <= 20; i++) {
        //            studentList.add(new Student("Student " + i, "androidstudent" + i + "@gmail.com"));
        //
        //        }

        mSwipeRefreshLayout.setRefreshing(true);
    }

    @Override
    public void onRefresh() {
        mFeed.clear();
        mAdapter.notifyDataSetChanged();
        loadData(true);
        currentPage=1;
    }
}
trans by 2020-01-11T03:26:47Z

android-在RecyclerView.Adap中重写notifyItemChanged的动画

好吧,我有一个带适配器的RecyclerView,一切正常。 ArrayList数据集中的项目会定期更新。 因此,项目及其元素以及它们在列表中的位置都会发生变化。 只要发生任何事情,就可以通过简单的排序并手动调用这些方法来实现:

// swapping two items
Collections.swap(items, i, j);
itemsAdapter.notifyItemMoved(i, j);

// adding a new one
itemAdapter.notifyItemInserted(items.size());

// when updating valus
itemAdapter.notifyItemChanged(i);

后者是我痛苦的原因。 每次更新项目时,都会触发一点“闪烁”动画。

我找到了一些解决方案:

// disabling all animations
recyclerView.getItemAnimator().setSupportsChangeAnimations(false);

// or

// setting the animation duration to zero,
recyclerView.getItemAnimator().setChangeDuration(0);

但是当物品移动(被交换)时,这两个都会杀死动画。 我只想覆盖一个动画并保留所有这些魔术。 有办法吗? 而且,如果它覆盖了ItemAnimator,那么有人能举一个简单的例子吗?

提前致谢!

trans by 2020-01-10T03:06:31Z

android-如何获取在RecyclerView中选择的位置?

我正在尝试使用支持库的recyclerview和卡。 我有一张纸的recyclerview。 每张卡的右上角都有一个“ x”图标以将其删除:

卡xml,onClick.

<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.CardView
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_margin="5dp">
<RelativeLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent">
    <TextView
        android:id="@+id/taskDesc"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:textSize="40sp"
        android:text="hi"/>
    <ImageView
        android:id="@+id/xImg"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:layout_alignParentRight="true"
        android:src="@drawable/ic_remove"/>
</RelativeLayout>
</android.support.v7.widget.CardView>

我试图用onClick.TaskAdapter.java中使用的位置标记行:

public class TaskAdapter extends RecyclerView.Adapter<TaskAdapter.TaskViewHolder>  {

private List<Task> taskList;
private TaskAdapter thisAdapter = this;


// cache of views to reduce number of findViewById calls
public static class TaskViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
    protected TextView taskTV;
    protected ImageView closeBtn;
    public TaskViewHolder(View v) {
        super(v);
        taskTV = (TextView)v.findViewById(R.id.taskDesc);
    }

    @Override
    public void onClick(View v) {
        int position = v.getTag();
        adapter.notifyItemRemoved(position);
    }
}


public TaskAdapter(List<Task> tasks) {
    if(tasks == null)
        throw new IllegalArgumentException("tasks cannot be null");
    taskList = tasks;
}


// onBindViewHolder binds a model to a viewholder
@Override
public void onBindViewHolder(TaskViewHolder taskViewHolder, int pos) {
    final int position = pos;
    Task currTask = taskList.get(pos);
    taskViewHolder.taskTV.setText(currTask.getDescription());

    taskViewHolder.closeBtn.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            thisAdapter.notifyItemRemoved(position);
        }
    });
}

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


// inflates row to create a viewHolder
@Override
public TaskViewHolder onCreateViewHolder(ViewGroup parent, int pos) {
    View itemView = LayoutInflater.from(parent.getContext()).
                                   inflate(R.layout.list_item, parent, false);

    return new TaskViewHolder(itemView);
}
}

这将无法工作,因为您无法设置标签,也无法从onClick.访问适配器

trans by 2020-01-08T19:00:06Z

如何从Android中的RecyclerView适配器获取物品

在旧代码中,当我将RecyclerView与自定义适配器一起使用时,我可以使用此代码获得商品。

Message msg = (Message) adapter.getItem(poistion);

现在,我正在实施RecyclerView。如何从RecyclerView.adapter中获取项目?

trans by 2020-01-02T03:17:09Z

android-使用RecyclerView时出错:指定的孩子已经有父母

我正在尝试使用新的RecyvlerView适配器创建listView。 我已按照android开发人员资源中提供的确切指南进行操作。 但这给了我一个奇怪的错误:指定的孩子已经有一个父母。 您必须先在孩子的父母上调用removeView()。我有最新的SDK。 我还在gradle中定义了依赖关系。

MyActivity(主要活动):

public class MyActivity extends Activity {

    private RecyclerView mRecyclerView;
    private RecyclerView.Adapter mAdapter;
    private RecyclerView.LayoutManager mLayoutManager;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_my);
        mRecyclerView = (RecyclerView) findViewById(R.id.my_recycler_view);

        // use this setting to improve performance if you know that changes
        // in content do not change the layout size of the RecyclerView
        mRecyclerView.setHasFixedSize(true);

        // use a linear layout manager
        mRecyclerView.setLayoutManager(new LinearLayoutManager(this));
        mRecyclerView.setItemAnimator(new DefaultItemAnimator());

        // specify an adapter (see also next example)
        mAdapter = new MyAdapter(new String[]{"Zain", "Nadeem"});

        mRecyclerView.setAdapter(mAdapter);
    }
}

MyAdapter:

public class MyAdapter extends RecyclerView.Adapter<MyAdapter.ViewHolder> {
    private String[] mDataset;    
    // Provide a reference to the views for each data item
    // Complex data items may need more than one view per item, and
    // you provide access to all the views for a data item in a view holder
    // Provide a suitable constructor (depends on the kind of dataset)
    public MyAdapter(String[] myDataset) {
        mDataset = myDataset;
    }

    // Create new views (invoked by the layout manager)
    @Override
    public MyAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        // create a new view
        LayoutInflater inflater = LayoutInflater.from(parent.getContext());  

        View v = inflater.inflate(R.layout.my_text_view, parent, true);
        ViewHolder vh = new ViewHolder(v);
        return vh;
    }

    // Replace the contents of a view (invoked by the layout manager)
    @Override
    public void onBindViewHolder(ViewHolder holder, int position) {
        // - get element from your dataset at this position
        // - replace the contents of the view with that element    
        holder.mTextView.setText(mDataset[position]);
    }

    // Return the size of your dataset (invoked by the layout manager)
    @Override
    public int getItemCount() {
        return mDataset.length;
    }

    public static class ViewHolder extends RecyclerView.ViewHolder {
        // each data item is just a string in this case
        public TextView mTextView;
        public ViewHolder(View v) {
            super(v);
            mTextView = (TextView) v.findViewById(R.id.item_title);
        }
    }
}

my_text_view.xml(列表项的布局):

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="80dp"

    >
    <!-- title -->
    <TextView
        android:id="@+id/item_title"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:textColor="@android:color/darker_gray"
        android:layout_marginLeft="8dp"
        android:layout_marginRight="8dp"
        android:layout_marginTop="8dp"
        android:textSize="22dp" />

</RelativeLayout>

activity_my.xml(主要活动):

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    xmlns:card_view="http://schemas.android.com/apk/res-auto"
    android:layout_height="fill_parent"
    android:layout_width="fill_parent"
    android:background="@android:color/holo_orange_light"
    >
    <!-- A CardView that contains a TextView -->
    <android.support.v7.widget.RecyclerView
        android:id="@+id/my_recycler_view"
        android:scrollbars="vertical"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        tools:context=".MyActivity"/>
    </LinearLayout>

这是logcat的输出:

10-28 01:20:30.287  22729-22729/osman.zaingz.com.lollipop E/AndroidRuntime﹕ FATAL EXCEPTION: main
    Process: osman.zaingz.com.lollipop, PID: 22729
    java.lang.IllegalStateException: The specified child already has a parent. You must call removeView() on the child's parent first.
            at android.view.ViewGroup.addViewInner(ViewGroup.java:3562)
            at android.view.ViewGroup.addView(ViewGroup.java:3415)
            at android.view.ViewGroup.addView(ViewGroup.java:3360)
            at android.support.v7.widget.RecyclerView$4.addView(RecyclerView.java:322)
            at android.support.v7.widget.ChildHelper.addView(ChildHelper.java:79)
            at android.support.v7.widget.RecyclerView$LayoutManager.addViewInt(RecyclerView.java:4845)
            at android.support.v7.widget.RecyclerView$LayoutManager.addView(RecyclerView.java:4803)
            at android.support.v7.widget.RecyclerView$LayoutManager.addView(RecyclerView.java:4791)
            at android.support.v7.widget.LinearLayoutManager.layoutChunk(LinearLayoutManager.java:1316)
            at android.support.v7.widget.LinearLayoutManager.fill(LinearLayoutManager.java:1265)
            at android.support.v7.widget.LinearLayoutManager.onLayoutChildren(LinearLayoutManager.java:522)
            at android.support.v7.widget.RecyclerView.dispatchLayout(RecyclerView.java:1918)
            at android.support.v7.widget.RecyclerView.onLayout(RecyclerView.java:2155)
            at android.view.View.layout(View.java:14817)
            at android.view.ViewGroup.layout(ViewGroup.java:4631)
            at android.widget.LinearLayout.setChildFrame(LinearLayout.java:1671)
            at android.widget.LinearLayout.layoutHorizontal(LinearLayout.java:1660)
            at android.widget.LinearLayout.onLayout(LinearLayout.java:1436)
            at android.view.View.layout(View.java:14817)
            at android.view.ViewGroup.layout(ViewGroup.java:4631)
            at android.widget.FrameLayout.layoutChildren(FrameLayout.java:453)
            at android.widget.FrameLayout.onLayout(FrameLayout.java:388)
            at android.view.View.layout(View.java:14817)
            at android.view.ViewGroup.layout(ViewGroup.java:4631)
            at com.android.internal.widget.ActionBarOverlayLayout.onLayout(ActionBarOverlayLayout.java:374)
            at android.view.View.layout(View.java:14817)
            at android.view.ViewGroup.layout(ViewGroup.java:4631)
            at android.widget.FrameLayout.layoutChildren(FrameLayout.java:453)
            at android.widget.FrameLayout.onLayout(FrameLayout.java:388)
            at android.view.View.layout(View.java:14817)
            at android.view.ViewGroup.layout(ViewGroup.java:4631)
            at android.view.ViewRootImpl.performLayout(ViewRootImpl.java:1983)
            at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:1740)
            at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:996)
            at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:5600)
            at android.view.Choreographer$CallbackRecord.run(Choreographer.java:761)
            at android.view.Choreographer.doCallbacks(Choreographer.java:574)
            at android.view.Choreographer.doFrame(Choreographer.java:544)
            at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:747)
            at android.os.Handler.handleCallback(Handler.java:733)
            at android.os.Handler.dispatchMessage(Handler.java:95)
            at android.os.Looper.loop(Looper.java:136)
            at android.app.ActivityThread.main(ActivityThread.java:5001)
            at java.lang.reflect.Method.invoke(Native Method)
            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:785)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:601)
trans by 2020-01-01T03:50:56Z

android-使用GridLayoutManager和RecyclerVi更改列数

在片段中,我通过以下方式设置GridLayout:2

因此,我只想在用户旋转手机/平板电脑时将2更改为4。 我已经阅读了onConfigurationChanged的内容,并尝试使其适用于我的情况,但处理方式不正确。 当我旋转手机时,应用程序崩溃了...

你能告诉我如何解决这个问题吗?

这是我找到解决方案的方法,该方法无法正常工作:

  @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);

        int orientation = newConfig.orientation;

        if (orientation == Configuration.ORIENTATION_PORTRAIT) {
            mRecycler.setLayoutManager(new GridLayoutManager(mContext, 2));
        } else if (orientation == Configuration.ORIENTATION_LANDSCAPE) {
            mRecycler.setLayoutManager(new GridLayoutManager(mContext, 4));
        }
    }

提前致谢!

trans by 2019-12-31T07:57:46Z

android-如何将RecyclerView放在NestedScrollView中?

通过创建NestedScrollView,您可以将滚动视图放入另一个滚动视图中,只要它们正确实现了NestedScrollingChild和NestedScrollingParent。

(这是不错的设计模式,“ Ian Lake(来自Google)实际上建议将CheeseDetailActivity放在此处的嵌套滚动视图中:plus.google.com/u/0/+AndroidDevelopers/posts/9kZ3SsXdT2T”)

我想将RecyclerView放在NestedScrollView内,幸运的是RecyclerView实现了NestedScrollingChild,因此您可以将其放入NestedScrollView。

public class RecyclerView extends ViewGroup implements ScrollingView, NestedScrollingChild

我已阅读以下帖子:

如何在NestedScrollView中使用RecyclerView?

在CoordinatorLayout内部使用NestedScrollView,RecyclerView(水平)进行NestedScrolling

但是投票最多的解决方案的问题是,它调用CheeseDetailActivity的所有项目,因此例如,如果它是一个无限的RecyclerView,并且当用户到达列表的末尾时您要发出网络请求,则使用该解决方案进行NestedScrollView调用 服务器重复,因为它会自动到达RecyclerView的最后一项。

无论如何,如何设置参数,这样我就可以将CheeseDetailActivity放在NestedScrollView内。

当我将CheeseDetailActivity放入NestedScrollView时,没有任何显示。


为了创建一个示例项目,您可以使用cheesesquare并将CheeseDetailActivity更改为具有RecyclerView。


尽管BNK的答案不正确,但BNK已经尝试了很多。 所以我授予他赏金。 仍在寻找不错的解决方案。

trans by 2019-12-30T00:13:12Z

1 2 3 4 5 6 下一页 共6页