使用常见的RowLayout时,处理ListView行按钮单击

时间:2016-04-05 07:27:10

标签: android listview listviewitem

我有一个ListAdapterListView RowLayout,我在2个片段中使用了ListView s。问题是如何处理ListView项目行按钮单击。公共RowLayout中有2个按钮,无论显示的片段如何,这些按钮都具有相同的功能。我搜索了它并找到了解决方案here。但是在这个帖子按钮中,只有在我有两个片段时才会调用一个活动。那么我们如何在Adapter中确保从单击其布局按钮调用特定片段?

ListAdapter

public class ListAdapter extends ArrayAdapter<GridItem> {

    private Context mContext;
    int resource;
    private ArrayList<GridItem> mListData = new ArrayList<GridItem>();

    public ListAdapter(Context mContext, int resource, ArrayList<GridItem> mListData) {
        super(mContext, resource, mListData);
        this.resource = resource;
        this.mContext = mContext;
        this.mListData = mListData;
    }

    public void setListData(ArrayList<GridItem> mListData) {
        this.mListData = mListData;
        notifyDataSetChanged();
    }

    @Override
    public GridItem getItem(int position) {
        return super.getItem(position);
    }



    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        View v = convertView;

        ViewHolder holder;
        if (v == null) {
            holder = new ViewHolder();
            LayoutInflater inflater = ((Activity) mContext).getLayoutInflater();

            v = inflater.inflate(resource, parent, false);
            holder.image = (ImageView) v.findViewById(R.id.item_image);
            holder.name = (TextView) v.findViewById(R.id.item_name);
            holder.regtdemail = (TextView) v.findViewById(R.id.item_regtdemail);
            holder.follow = (Button)v.findViewById(R.id.follow);
            holder.remove = (Button)v.findViewById(R.id.remove);

            v.setTag(holder);
        } else {
            holder = (ViewHolder) v.getTag();
        }


        GridItem item = mListData.get(position);
        Picasso.with(mContext)
                .load(item.getImage())
                .placeholder(R.drawable.placeholder)
                .fit()
                .into(holder.image);
        holder.name.setText(item.getName());
        holder.regtdemail.setText(item.getRegtdEmail());
        holder.follow.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

            }
        });

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

            }
        });


        return v;
    }

    class ViewHolder {
        ImageView image;
        TextView name, regtdemail;
        Button follow, remove;
    }

}

第二片段:

public class SuggestFriend extends Fragment{

    private ListView mListView;
    private GridItem newItem;
    private ListAdapter mListAdapter;
    private ArrayList<GridItem> mGridData;
    public static final String KEY_USERID = "user_id", SPORTS_ID = "sports_id";
    private static final String MUTUAL_FOLLOWERS = "http://example.com/api/member/follow-suggestions/";

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        return inflater.inflate(R.layout.suggestfriend, container, false);
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);

        mListView = (ListView)view.findViewById(R.id.list_view);
        mGridData = new ArrayList<>();
        mListAdapter = new ListAdapter(getContext(), R.layout.common_row, mGridData);
        mListView.setAdapter(mListAdapter);

        loadmutualfollowers();

    }

    private void loadmutualfollowers() {
        StringRequest stringRequest = new StringRequest(Request.Method.POST, MUTUAL_FOLLOWERS,
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {

                        try {
                            JSONObject jObj = new JSONObject(response);

                            System.out.println(jObj);

                            String status = jObj.getString("status");

                            // Now check status value
                            if (status.equals("0")) {
                                Toast.makeText(getActivity(), "There was some error! Please try again.", Toast.LENGTH_LONG).show();
                            } else if (status.equals("1")) {


                                JSONArray result = jObj.getJSONArray("result");
                                for (int i = 0; i < result.length(); i++) {
                                    JSONObject json_data = result.getJSONObject(i);
                                    String name = json_data.getString("name");
                                    String regtdemail = json_data.getString("username");
                                    String user_id = json_data.getString("user_id");

                                    newItem = new GridItem();

                                    newItem.setName(name);
                                    newItem.setRegtdEmail(regtdemail);
                                    newItem.setUserId(user_id);
                                    if(json_data.has("profile_picture")){

                                        newItem.setImage(json_data.getString("profile_picture"));

                                    }else{

                                        Uri path = Uri.parse("android.resource://com.sam.fitlincsearch/" + R.drawable.default_profile);
                                        String image_def = path.toString();
                                        newItem.setImage(image_def);

                                    }


                                    mGridData.add(newItem);
                                }


                                mListAdapter.notifyDataSetChanged();

                            } else {
                                String errorMsg = jObj.getString("error_msg");
                                Toast.makeText(getActivity(), errorMsg, Toast.LENGTH_LONG).show();
                            }
                        } catch (JSONException e) {
                            // JSON error
                            e.printStackTrace();
                            Toast.makeText(getActivity(), "Json error: " + e.getMessage(), Toast.LENGTH_LONG).show();
                        }
                    }
                }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                Toast.makeText(getActivity(), "VolleyError" + error.toString(), Toast.LENGTH_LONG).show();
            }
        }) {
            @Override
            protected Map<String, String> getParams() {
                Map<String, String> params = new HashMap<String, String>();
                params.put(KEY_USERID, "1");  
                return params;
            }

        };

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

第一段:

public class TopContenders extends Fragment {

    private ListView mListView;
    private GridItem newItem;
    private ListAdapter mListAdapter;
    private ArrayList<GridItem> mGridData;
    public static final String KEY_USERID = "user_id", SPORTS_ID = "sports_id";
    private static final String TOP_MEMBERS = "http://example.com/api/top-member/";
    Button follow, unfollow;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        return inflater.inflate(R.layout.topcontenders, container, false);
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);

        mListView = (ListView)view.findViewById(R.id.list_view);
        mGridData = new ArrayList<>();
        mListAdapter = new ListAdapter(getContext(), R.layout.common_row, mGridData);
        mListView.setAdapter(mListAdapter);

        loadtopmembers();
    }

    private void loadtopmembers() {
        StringRequest stringRequest = new StringRequest(Request.Method.POST, TOP_MEMBERS,
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {

                        try {
                            JSONObject jObj = new JSONObject(response);

                            System.out.println(jObj);

                            String status = jObj.getString("status");

                            // Now check status value
                            if (status.equals("0")) {
                                Toast.makeText(getActivity(), "There was some error! Please try again.", Toast.LENGTH_LONG).show();
                            } else if (status.equals("1")) {


                                JSONArray result = jObj.getJSONArray("result");
                                for (int i = 0; i < result.length(); i++) {
                                    JSONObject json_data = result.getJSONObject(i);
                                    String name = json_data.getString("name");
                                    String regtdemail = json_data.getString("username");
                                    String user_id = json_data.getString("user_id");
                                    String sports_id = json_data.getString("sports_id");

                                    newItem = new GridItem();

                                    newItem.setName(name);
                                    newItem.setRegtdEmail(regtdemail);
                                    newItem.setUserId(user_id);
                                    if(json_data.has("profile_picture")) {
                                        newItem.setImage(json_data.getString("profile_picture"));

                                    }else{

                                        Uri path = Uri.parse("android.resource://com.sam.fitlincsearch/" + R.drawable.default_profile);
                                        String image_def = path.toString();
                                        newItem.setImage(image_def);

                                    }
                             /*     if(sports_id.equals("1")){
                                      newItem.setSportsId("Weight");
                                  }else if(sports_id.equals("2")){
                                      newItem.setSportsId("Cycle");
                                  }else if(sports_id.equals("3")){
                                      newItem.setSportsId("Swim");
                                  }else if(sports_id.equals("4")){
                                      newItem.setSportsId("Run");
                                  } */

                                    mGridData.add(newItem);
                                }


                                mListAdapter.notifyDataSetChanged();

                            } else {
                                String errorMsg = jObj.getString("error_msg");
                                Toast.makeText(getActivity(), errorMsg, Toast.LENGTH_LONG).show();
                            }
                        } catch (JSONException e) {
                            // JSON error
                            e.printStackTrace();
                            Toast.makeText(getActivity(), "Json error: " + e.getMessage(), Toast.LENGTH_LONG).show();
                        }
                    }
                }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                Toast.makeText(getActivity(), "VolleyError" + error.toString(), Toast.LENGTH_LONG).show();
            }
        }) {
            @Override
            protected Map<String, String> getParams() {
                Map<String, String> params = new HashMap<String, String>();
                params.put(KEY_USERID, "1");  
                return params;
            }

        };

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

1 个答案:

答案 0 :(得分:0)

您可以在适配器getView()方法中将当前视图设置为按钮,在button.setOnClickListener()中,您可以获取此视图并执行任何操作。 使用setTag()getTag()

示例:

在适配器getView()中:

holder.btnPlus = (Button) convertView.findViewById(R.id.btnPlusdessert);
    holder.btnPlus.setTag(R.integer.btnplusview,convertView);

按钮onClickListener()

holder.btnPlus.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                View tempView =(View) v.getTag(R.integer.btnplusview);

现在您可以看到行布局的完整视图,您可以使用tempView获取其他textview或按钮或其他内容。