如何从RecyclerView Adapter传递给MainActivity的变量?

时间:2019-07-08 09:29:04

标签: java android android-recyclerview

当我遇到这个问题时,我只是在玩弄一些代码,学习新东西...我正在尝试将RecylcerViewAdapter中的变量传递给MainActivity中的方法,但是我似乎无法完成它。

我在接口和转换方面尝试了很多不同的方法,但是没有成功。由于我对所有这些都还比较陌生,也许我在某个地方犯了一个小错误?

我的界面:

public interface AdapterCallback {
    void onMethodCallback(int id);
} 

这是我的适配器类:

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

    private List<Post> postList;
    private Context context;
    private AdapterCallback listener;

    public PostAdapter() {
    }

    public PostAdapter(List<Post> postList, Context context) {
        this.postList = postList;
        this.context = context;
    }

    public void setListener(AdapterCallback listener) {
        this.listener = listener;
    }

    @NonNull
    @Override
    public ViewHolder onCreateViewHolder(@NonNull ViewGroup viewGroup, int i) {
        View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.recycler_layout, viewGroup, false);
        return new ViewHolder(view);
    }

    @Override
    public void onBindViewHolder(@NonNull final ViewHolder viewHolder, final int position) {
        viewHolder.tvTitle.setText(postList.get(position).getTitle());
        viewHolder.tvBody.setText(new StringBuilder(postList.get(position).getBody().substring(0, 20)).append("..."));
        viewHolder.tvId.setText(String.valueOf(postList.get(position).getUserId()));

        viewHolder.parentLayout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                int id = postList.get(position).getId();
                if (listener != null) {
                    listener.onMethodCallback(id);
                }
            }
        });
    }

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

    public class ViewHolder extends RecyclerView.ViewHolder {

        TextView tvTitle;
        TextView tvBody;
        TextView tvId;
        LinearLayout parentLayout;

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

            tvTitle = itemView.findViewById(R.id.tvTitle);
            tvBody = itemView.findViewById(R.id.tvBody);
            tvId = itemView.findViewById(R.id.tvId);
            parentLayout = itemView.findViewById(R.id.parentLayout);
        }
    }
}
And my MainActivity:

public class MainActivity extends AppCompatActivity {

    public static final String TAG = "MainActivityLog";
    private CompositeDisposable disposable = new CompositeDisposable();

    @BindView(R.id.rvPosts)
    RecyclerView rvPosts;

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

        ButterKnife.bind(this);

        rvPosts.setHasFixedSize(true);
        rvPosts.setLayoutManager(new LinearLayoutManager(this));

        populateList();
        logItems();
    }

    private void populateList() {
        MainViewModel viewModel = ViewModelProviders.of(MainActivity.this).get(MainViewModel.class);
        viewModel.makeQuery().observe(MainActivity.this, new Observer<List<Post>>() {
            @Override
            public void onChanged(@Nullable List<Post> posts) {
                PostAdapter adapter = new PostAdapter(posts, getApplicationContext());
                rvPosts.setAdapter(adapter);
            }
        });
    }

    public void logItems() {
        PostAdapter adapter = new PostAdapter();
        adapter.setListener(new AdapterCallback() {
            @Override
            public void onMethodCallback(int id) {
                MainViewModel viewModel = ViewModelProviders.of(MainActivity.this).get(MainViewModel.class);
                viewModel.makeSingleQuery(id).observe(MainActivity.this, new Observer<Post>() {
                    @Override
                    public void onChanged(@Nullable final Post post) {
                        Log.d(TAG, "onChanged: data response");
                        Log.d(TAG, "onChanged: " + post);
                    }
                });
            }
        });
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        disposable.clear();
    }
}

populateList()方法可以正常工作,但是logItems()方法是问题所在。

因此,当我在RecyclerView中单击视图时,我希望日志输出被单击的帖子的标题,描述和ID。没事...

因此,我们将不胜感激。

4 个答案:

答案 0 :(得分:0)

设置适配器全局变量,即字段。使用同一对象设置每个属性。

        var models = [
          {
            name: 'Bear',
            load: function(model) {
              stlLoader.load(
                '{{ url_for('static', filename='bear.stl') }}',
                function(geometry) {
                  // Regenerate normals because they aren't loaded properly.
                  geometry.computeFaceNormals();
                  geometry.computeVertexNormals();
                  // Load the model and build mesh.
                  var material = new THREE.MeshBasicMaterial( {color:0xffff00} );
                  model.model = new THREE.Mesh(geometry, material);
                  // Rotate, scale, and move so the bear is facing out the screen.
                  model.model.rotation.x = -90 * (Math.PI / 180.0);
                  model.model.scale.set(0.15, 0.15, 0.15);
                  model.model.position.y = -4;
                }

为此替换您的private PostAdapter adapter; 方法:

logItems

然后使用以下方法填充列表:

public void logItems() {
    adapter.setListener(new AdapterCallback() {
        @Override
        public void onMethodCallback(int id) {
            MainViewModel viewModel = ViewModelProviders.of(MainActivity.this).get(MainViewModel.class);
            viewModel.makeSingleQuery(id).observe(MainActivity.this, new Observer<Post>() {
                @Override
                public void onChanged(@Nullable final Post post) {
                    Log.d(TAG, "onChanged: data response");
                    Log.d(TAG, "onChanged: " + post);
                }
            });
        }
    });
}

也不要从private void populateList() { MainViewModel viewModel = ViewModelProviders.of(MainActivity.this).get(MainViewModel.class); viewModel.makeQuery().observe(MainActivity.this, new Observer<List<Post>>() { @Override public void onChanged(@Nullable List<Post> posts) { adapter = new PostAdapter(posts, getApplicationContext()); rvPosts.setAdapter(adapter); logItems(); } }); } 呼叫logItems()

答案 1 :(得分:0)

onPopulateList中创建一个适配器:

 PostAdapter adapter = new PostAdapter(posts, getApplicationContext());
            rvPosts.setAdapter(adapter);

但是在public void logItems() {中,您使用了其他适配器

 PostAdapter adapter = new PostAdapter();
    adapter.setListener(new AdapterCallback() {
        @Override
        public void onMethodCallback(int id) {
            ...
        }
    });

因此,该列表中填充了1个适配器,但是您将监听器设置在未使用的第二个适配器上。


解决方法是对两者使用相同的适配器。如果将adapater设置为一个字段,并且不要在logItems内创建一个新字段,而只需将其设置为监听器即可。

 // as a field in your class
 private PostAdapter adapter;

然后

 // in `populateList()` 
 adapter = new PostAdapter(posts, getApplicationContext());
 rvPosts.setAdapter(adapter);

 // in `logItems()`
 adapter.setListener(new AdapterCallback() {
    @Override
    public void onMethodCallback(int id) {
        ...
    }
});

答案 2 :(得分:0)

这是我使用ListAdapters实现的方式:

$associatedUsers = $groupMembers->users()->whereIn('users.id', $request->get('group_members'))->pluck('users.id'); // It'll give all attached user IDs

if(!$unAssociatedUserIds = array_diff($request->get('group_members'), $associatedUsers)) {
            // throw error message
           // return response
        }
$groupMembers->users()->attach($unAssociatedUserIds);

}

答案 3 :(得分:0)

在适配器中

public class CustomerListAdapter extends RecyclerView.Adapter<CustomerListAdapter.OrderItemViewHolder> {

    private Context mCtx;
    ProgressDialog progressDialog;

    //we are storing all the products in a list
    private List<CustomerModel> customeritemList;


    public CustomerListAdapter(Context mCtx, List<CustomerModel> orderitemList) {
        this.mCtx = mCtx;
        this.customeritemList = orderitemList;
        progressDialog = new ProgressDialog(mCtx);
    }

    @NonNull
    @Override
    public OrderItemViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {

        LayoutInflater inflater = LayoutInflater.from(mCtx);
        View view = inflater.inflate(R.layout.activity_customer_list, null);
        return new OrderItemViewHolder(view, mCtx, customeritemList);
    }

    @Override
    public void onBindViewHolder(@NonNull OrderItemViewHolder holder, int position) {
        CustomerModel customer = customeritemList.get(position);
        try {
            //holder.textViewPINo.setText("PINo \n"+Integer.toString( order.getPINo()));
            holder.c_name.setText(customer.getCustomerName());
            holder.c_address.setText(customer.getAddress());
            holder.c_contact.setText(customer.getMobile());
            holder.i_name.setText(customer.getInteriorName());
            holder.i_contact.setText(customer.getInteriorMobile());
            holder.i_address.setText(customer.getAddress());

        } catch (Exception E) {
            E.printStackTrace();
        }
    }


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

    class OrderItemViewHolder extends RecyclerView.ViewHolder implements View.OnLongClickListener, View.OnClickListener {
        AlertDialog.Builder alert;
        private Context mCtx;

        TextView c_name, c_contact, c_address, i_name, i_contact, i_address;
        TextView OrderItemID, MaterialType, Price2, Qty, AQty;

        //we are storing all the products in a list
        private List<CustomerModel> orderitemList;


        public OrderItemViewHolder(View itemView, Context mCtx, List<CustomerModel> orderitemList) {
            super(itemView);
            this.mCtx = mCtx;
            this.orderitemList = orderitemList;

            itemView.setOnClickListener(this);
            itemView.setOnLongClickListener(this);

            // CatelogOrderDetailModel catelogOrderDetailModel = new CatelogOrderDetailModel();
            c_name = itemView.findViewById(R.id.customerName);
            c_contact = itemView.findViewById(R.id.contact);
            c_address = itemView.findViewById(R.id.address);
            i_name = itemView.findViewById(R.id.interiorName);
            i_address = itemView.findViewById(R.id.interiorAddress);
            i_contact = itemView.findViewById(R.id.interiorContact);
        }

        @Override
        public void onClick(View v) {
            int position = getAdapterPosition();
            CustomerModel orderitem = this.orderitemList.get(position);

        }

        @Override
        public boolean onLongClick(View v) {

            int position = getAdapterPosition();
            CustomerModel orderitem = this.orderitemList.get(position);

            if (v.getId() == itemView.getId()) {
                // showUpdateDeleteDialog(order);
                try {

                } catch (Exception E) {
                    E.printStackTrace();
                }
                Toast.makeText(mCtx, "lc: ", Toast.LENGTH_SHORT).show();
            }
            return true;
        }


    }
}