猿问

Android RecyclerView 仅在关闭并重新启动应用程序后显示项目

将应用程序更新到 API 28 后,我的 RecyclerView 出现了奇怪的效果。我有一个搜索按钮,可以触发对我所在区域的 Wifi 设备的搜索。这些项目不再直接显示在列表中。我必须关闭并重新打开应用程序才能获得正确的显示。


我有一个在按下按钮时应该显示的吐司。Toast 消息也仅在关闭和打开应用程序后显示。


活动.kt


   private fun setFloatingSearchButton() {

        floating_button_discover_devices.setOnClickListener { view ->

            Snackbar.make(view, "Search for new devices ...",

                    Snackbar.LENGTH_SHORT).setAction("Action", null).show()


            discoverDevices()


            registerReceiver(mWifiReceiver, IntentFilter(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION))


            mWifiManager!!.startScan()

        }

    }

WifiAdapter.java


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


    private final int CONFIGURE_DEVICE_REQUEST_CODE = 0x00000001;


    private static final String TAG = "WifiAdapter";


    private List<DeviceWifiTo> wifis;


    private Context context;

    private Activity activity;


    public WifiAdapter(List<DeviceWifiTo> wifis) {

        this.wifis = wifis;

    }


    @Override

    public WifiAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {

        context = parent.getContext();

        activity = (Activity) context;

        LayoutInflater inflater = LayoutInflater.from(context);


        View wifiView = inflater.inflate(R.layout.item_wifi, parent, false);


        return new WifiAdapter.ViewHolder(wifiView);

    }


    @Override

    public void onBindViewHolder(WifiAdapter.ViewHolder holder, int position) {

        DeviceWifiTo wifi = wifis.get(position);

        Log.d(TAG, wifi.getSsid());

        TextView wifiName = holder.wifiName;

        wifiName.setText(wifi.getSsid());


        CardView cardView = holder.cardView;

        cardView.setOnClickListener(view -> {

            Intent intent = new Intent(context, ConfigureDeviceActivity.class);

            intent.putExtra("ssid", wifi.getSsid());

            activity.startActivityForResult(intent, CONFIGURE_DEVICE_REQUEST_CODE);

        });

    }

人到中年有点甜
浏览 111回答 4
4回答

慕仙森

layout manager之前设置为adapter,recycler view更新如下private void createRecyclerView(List<DeviceWifiTo> list) {&nbsp; &nbsp;RecyclerView recyclerView = activity.findViewById(R.id.recycler_view_wifi);&nbsp; &nbsp;recyclerView.setLayoutManager(new LinearLayoutManager(activity.getApplicationContext()));&nbsp; &nbsp;WifiAdapter adapter = new WifiAdapter(list);&nbsp; &nbsp;recyclerView.setAdapter(adapter);}希望对您有帮助。

qq_遁去的一_1

layoutmanager在设置之前尝试设置adapter

大话西游666

我猜你想在 recyclerView 中显示你的结果。您的搜索有回调方法吗?您需要在该回调方法中调用notifyDataSetChanged()(设置结果然后调用notifyDataSetChanged())

喵喔喔

我在 kotlin 中遇到了类似的问题,只是因为没有添加notifyDataSetChanged()我设置数据的位置。
随时随地看视频慕课网APP

相关分类

Java
我要回答