如何将数据从适配器返回到活动

时间:2017-03-15 10:30:05

标签: java android android-recyclerview

我有一个包含RecyclerView的活动,我展示了一些来自服务器的数据。问题是我在MYAdapter类中设置了RecyclerView的onCLick,但现在我需要根据包含RecyclerView的Activity的一些数据处理OnClick of RecyclerView。

public class ActivityAllUsers extends AppCompatActivity {

private RecyclerView recyclerView;
private RecyclerView.Adapter adapter;
private List<ListItem> listitems;

private static final String URL_DATA = "http://shayea.tk/sof/get_allusers.php";
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    int id = getIntent().getIntExtra("IDUSERTYPE", 0);// -1 is default value

    recyclerView = (RecyclerView) findViewById(R.id.recyvlerview);
    recyclerView.setHasFixedSize(true);
    recyclerView.setLayoutManager(new LinearLayoutManager(this));

    listitems = new ArrayList<>();

    loadRecyclerviewData();
}

private void loadRecyclerviewData()
{
    final ProgressDialog dialog = new ProgressDialog(this);
    dialog.setMessage("Loading...");
    dialog.show();

    StringRequest stringRequest = new StringRequest(Request.Method.GET, URL_DATA, new Response.Listener<String>() {
        @Override
        public void onResponse(String s) {
                dialog.dismiss();
            try {
                JSONObject jsonObject = new JSONObject(s);
                JSONArray array = jsonObject.getJSONArray("result");

                for (int i =0;i<array.length();i++)
                {
                    JSONObject o = array.getJSONObject(i);
                    ListItem item = new ListItem(
                            o.getString("usr_id"),
                            o.getString("usr_name"),
                            o.getString("usr_phone"),
                            o.getString("usr_email"),
                            o.getString("usr_status"),
                            o.getString("prv_name"),
                            o.getString("org_name")
                    );

                    listitems.add(item);
                }

                adapter = new MyAdapter(listitems , getApplicationContext());
                recyclerView.setAdapter(adapter);
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
    }, new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {
            dialog.dismiss();
            Toast.makeText(getApplicationContext(),error.getMessage(), Toast.LENGTH_LONG).show();
        }
    });

    RequestQueue requestQueue = Volley.newRequestQueue(this);
    requestQueue.add(stringRequest);
}
}

我希望当这个int id = getIntent().getIntExtra("IDUSERTYPE", 0); ID 包含 1 id 包含任何内容时,可以使用OnClick of RecyclerView否则OnClick不应该是活动的。 这是 MyAdapter 类,其中包含OnClick of RecyclerView:

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

private List<ListItem> listItems;
private Context context;

public MyAdapter(List<ListItem> listItems, Context context) {
    this.listItems = listItems;
    this.context = context;
}

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

@Override
public void onBindViewHolder(ViewHolder holder, final int position) {

    final ListItem listItem = listItems.get(position);

    holder.txtusername.setText(listItem.getusername());
    holder.txtuseremail.setText(listItem.getEmail());

    holder.linearLayout.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            Intent intent = new Intent(context, UserInformation.class);
            intent.putExtra("Details", (Serializable) listItem);
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            context.startActivity(intent);

        }
    });
}

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

public class ViewHolder extends RecyclerView.ViewHolder{

    public TextView txtusername;
    public TextView txtuseremail;
    public LinearLayout linearLayout;
    public ViewHolder(View itemView) {
        super(itemView);

        txtusername = (TextView) itemView.findViewById(R.id.textviewusername);
        txtuseremail = (TextView) itemView.findViewById(R.id.textviewuseremail);
        linearLayout = (LinearLayout) itemView.findViewById(R.id.linearlayout);
    }
}
}

我需要 ActivityAllUsers 中的 id ,我在这里:

 holder.linearLayout.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            Intent intent = new Intent(context, UserInformation.class);
            intent.putExtra("Details", (Serializable) listItem);
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            context.startActivity(intent);

        }
    });

4 个答案:

答案 0 :(得分:6)

  

问题是我已经设置了RecyclerView的onCLick   MYAdapter类,但现在我需要处理RecyclerView的OnClick   在一些数据,这是我的Activity包含   RecyclerView。

我认为根据您的要求,您需要更改标题:如何将数据从适配器返回到活动

在适配器中,您可以像这样创建回调

public interface AdapterCallback{
   void onItemClicked(int position);
}
AdapterCallback callback;
public MyAdapter(List<ListItem> listItems, Context context, AdapterCallback callback) {
    this.listItems = listItems;
    this.context = context;
    this.callback = callback;
}

...
holder.linearLayout.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            // You can move this block codes to Activity
            Intent intent = new Intent(context, UserInformation.class);
            intent.putExtra("Details", (Serializable) listItem);
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            context.startActivity(intent);
            //
            // callback here
            if(callback != null) {
              callback.onItemClicked(position)
            }

        }
    });

并在ActivityAllUsers

    public class ActivityAllUsers extends AppCompatActivity implements AdapterCallback {

   ...
   adapter = new MyAdapter(listitems , getApplicationContext(), ActivityAllUsers.this);

    ...

    @Override
    public void onItemClicked(int position){
        // call back here
    }

    }

答案 1 :(得分:1)

你可以通过像这样的适配器构造函数传递值

adapter = new MyAdapter(listitems , getApplicationContext(), value);

并在您的适配器类

int value = -1; //global variable with default value
public MyAdapter(List<ListItem> listItems, Context context, int value) {
    this.listItems = listItems;
    this.context = context;
    this.value = value;
}

以及稍后的onBindViewHolder

if(value == 1) {
holder.linearLayout.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            Intent intent = new Intent(context, UserInformation.class);
            intent.putExtra("Details", (Serializable) listItem);
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            context.startActivity(intent);

        }
    });
}

答案 2 :(得分:0)

定义适配器时,可以将数据传递给适配器。这是一个例子:

adapter = new MyAdapter(listitems , getApplicationContext(), data you want to send);

要接收,您必须编辑构造函数并使其像这样:

public MyAdapter(List<ListItem> listItems, Context context, String DataYou WantToReceive) 
{
    this.listItems = listItems;
    this.context = context;

this.data = DataYouWantToReceive     }

答案 3 :(得分:0)

试试这个,

        int id = getIntent().getIntExtra("IDUSERTYPE", 0);
        adapter = new MyAdapter(listitems , getApplicationContext(),id);
        recyclerView.setAdapter(adapter);


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

            private List<ListItem> listItems;
            private Context context;
            private int id;
            public MyAdapter(List<ListItem> listItems, Context context,int id) {
                this.listItems = listItems;
                this.context = context;
                this.id=id;
            }
            .
            .
            .

            @Override
            public void onBindViewHolder(ViewHolder holder, final int position) {

            final ListItem listItem = listItems.get(position);

            holder.txtusername.setText(listItem.getusername());
            holder.txtuseremail.setText(listItem.getEmail());

            holder.linearLayout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                Intent intent = new Intent(context, UserInformation.class);
                intent.putExtra("Details", (Serializable) listItem);
                intent.putExtra("ID", id);
                intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                context.startActivity(intent);

            }
        });

        }
});
        }