android如何选择setOnItemClickListener来获取正确的值

时间:2016-03-04 11:43:54

标签: android android-volley

android setOnItemClickListener无法正常工作如何选择值get 显示为ShareWithArticle @ 211f2370

To.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                        @Override
                        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                                String selected = String.valueOf(adapter.getItem(position));

                        }
                    });

我的代码

    public class CustomerAdapter extends ArrayAdapter<ShareWithArticle> {
    private final Context mContext;
    private final List<ShareWithArticle> mDepartments;
    private final List<ShareWithArticle> mDepartments_All;
    private final List<ShareWithArticle> mDepartments_Suggestion;
    private final int mLayoutResourceId;

    public CustomerAdapter(Context context, int resource, List<ShareWithArticle> departments) {
        super(context, resource, departments);
        this.mContext = context;
        this.mLayoutResourceId = resource;
        this.mDepartments = new ArrayList<>(departments);
        this.mDepartments_All = new ArrayList<>(departments);
        this.mDepartments_Suggestion = new ArrayList<>();
    }

    public int getCount() {
        return mDepartments.size();
    }

    public ShareWithArticle getItem(int position) {
        return mDepartments.get(position);
    }

    public long getItemId(int position) {
        return position;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        try {
            if (convertView == null) {
                LayoutInflater inflater = ((Activity) mContext).getLayoutInflater();
                convertView = inflater.inflate(mLayoutResourceId, parent, false);
            }
            ShareWithArticle department = getItem(position);
            final TextView name = (TextView) convertView.findViewById(R.id.textView2);
            final TextView userId = (TextView) convertView.findViewById(R.id.textView3);
            name.setText(department.getUsrCompNm());
            userId.setText(department.getUsrID() + "");
            convertView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    String userNm  =   name.getText().toString();
                    String userIdtxt = userId.getText().toString();

                   // userNm      how to pass values shareFragment
                    //userIdtxt     how to pass values shareFragment

                }
            });

        } catch (Exception e) {
            e.printStackTrace();
        }
        return convertView;
    }

    @Override
    public Filter getFilter() {
        return new Filter() {
            @Override
            public String convertResultToString(Object resultValue) {
                return ((ShareWithArticle) resultValue).getUsrCompNm();
            }

            @Override
            protected FilterResults performFiltering(CharSequence constraint) {
                if (constraint != null) {
                    mDepartments_Suggestion.clear();
                    for (ShareWithArticle department : mDepartments_All) {
                        if (department.getUsrCompNm().toLowerCase().startsWith(constraint.toString().toLowerCase())) {
                            mDepartments_Suggestion.add(department);
                        }
                    }
                    FilterResults filterResults = new FilterResults();
                    filterResults.values = mDepartments_Suggestion;
                    filterResults.count = mDepartments_Suggestion.size();
                    return filterResults;
                } else {
                    return new FilterResults();
                }
            }

            @Override
            protected void publishResults(CharSequence constraint, FilterResults results) {
                mDepartments.clear();
                if (results != null && results.count > 0) {
                    // avoids unchecked cast warning when using mDepartments.addAll((ArrayList<Department>) results.values);
                    List<?> result = (List<?>) results.values;
                    for (Object object : result) {
                        if (object instanceof ShareWithArticle) {
                            mDepartments.add((ShareWithArticle) object);
                        }
                    }
                } else if (constraint == null) {
                    // no filter, add entire original list back in
                    mDepartments.addAll(mDepartments_All);
                }
                notifyDataSetChanged();
            }
        };
    }

}

myFragment我的dialogFragment

    public class ShareFragment extends DialogFragment {
    private static final String ARG_PARAM1 = "param1";
    private static final String ARG_PARAM2 = "param2";
    private String mParam1;
    private String mParam2;
    VolleySingleton volleySingleton;
    private RequestQueue requestQueue;
    TextView share;
    EditText message;
    AutoCompleteTextView To;
    Context context;
    String articleID;
    ArrayList<ShareWithArticle> userList = new ArrayList<>();


    CustomerAdapter adapter;
    public ShareFragment() {
        // Required empty public constructor
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            mParam1 = getArguments().getString(ARG_PARAM1);
            mParam2 = getArguments().getString(ARG_PARAM2);
        }
        setStyle(DialogFragment.STYLE_NO_TITLE, R.style.alert_dialog);
        volleySingleton = VolleySingleton.getInstance();
        requestQueue = volleySingleton.getRequestQueue();
        articleID = getArguments().getString("ArticleId");

        Bundle bundle = new Bundle();
        String nms = bundle.getString("startFromWS");
        M.i("==============LS",""+nms);


    }

    public void postCompanyArticle(final String message, final String share) {

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

              //  M.i("==================SHARE", "" + response);
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                String msg = VolleyException.getErrorMessageFromVolleyError(error);
            }
        }) {
            @Override
            protected Map<String, String> getParams() throws AuthFailureError {
                Map<String, String> params = new HashMap<>();
                params.put("content_id", articleID);
                params.put("content_type", "article");
                params.put("message", message);
                params.put("share_with", share);
                return params;
            }
        };
        stringRequest.setRetryPolicy(
                new DefaultRetryPolicy(3 * 1000, 1, 1.0f));
        requestQueue.add(stringRequest);
    }
    @Override
    public void onDestroyView() {
        if (getDialog() != null && getRetainInstance())
            getDialog().setOnDismissListener(null);
        super.onDestroyView();
    }
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        final View view = inflater.inflate(R.layout.fragment_share, container, false);
        share = (TextView) view.findViewById(R.id.overCmt);
        To = (AutoCompleteTextView) view.findViewById(R.id.to);
        message = (EditText) view.findViewById(R.id.message);

        TextView cancel = (TextView) view.findViewById(R.id.overLink);
        cancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                getDialog().dismiss();
            }
        });
        share.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String to = To.getText().toString();
                String msg = message.getText().toString();
                postCompanyArticle(msg,to);
            }
        });

        To.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                UserTo(s.toString());
            }

            @Override
            public void afterTextChanged(Editable s) {
            }
        });
        return view;
    }

    public void UserTo(String share) {
        StringRequest stringRequest = new StringRequest(Request.Method.POST, ConfigApi.UserToArticle(), new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {
                //userList = ShareWithArticleJson.parseResponse(response);
                //adapter.setList(list);

                try {
                    JSONObject json = new JSONObject(response);
                    JSONArray data = json.getJSONArray(DATA);
                    for (int i = 0; i < data.length(); i++) {
                        ShareWithArticle ls = new ShareWithArticle();
                        JSONObject item = data.getJSONObject(i);
                        String name = item.getString("UsrFNm");
                        int UsrID = item.getInt("UsrID");

                        ShareWithArticle ll =new  ShareWithArticle();
                        ll.setUsrCompNm(name);
                        ll.setUsrID(UsrID);
                        userList.add(ll);

                    }

                    final CustomerAdapter adapter = new CustomerAdapter(getActivity(),R.layout.custom_share_adapter , userList);
                    To.setAdapter(adapter);
                    To.setThreshold(1);

                    To.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                        @Override
                        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                                String selected = String.valueOf(adapter.getItem(position));

                        }
                    });


                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                String msg = VolleyException.getErrorMessageFromVolleyError(error);
            }
        });
        stringRequest.setRetryPolicy(
                new DefaultRetryPolicy(3 * 1000, 1, 1.0f));
        requestQueue.add(stringRequest);
    }

}

3 个答案:

答案 0 :(得分:1)

public class FontFitTextView extends TextView {

    public FontFitTextView(Context context) {
        super(context);
        initialise();
    }

    public FontFitTextView(Context context, AttributeSet attrs) {
        super(context, attrs);
        initialise();
    }

    private void initialise() {
        mTestPaint = new Paint();
        mTestPaint.set(this.getPaint());
        //max size defaults to the initially specified text size unless it is too small
    }

    /* Re size the font so the specified text fits in the text box
     * assuming the text box is the specified width.
     */
    private void refitText(String text, int textWidth)
    {
        if (textWidth <= 0)
            return;
        int targetWidth = textWidth - this.getPaddingLeft() - this.getPaddingRight();
        float hi = 100;
        float lo = 2;
        final float threshold = 0.5f; // How close we have to be

        mTestPaint.set(this.getPaint());

        while((hi - lo) > threshold) {
            float size = (hi+lo)/2;
            mTestPaint.setTextSize(size);
            if(mTestPaint.measureText(text) >= targetWidth)
                hi = size; // too big
            else
                lo = size; // too small
        }
        // Use lo so that we undershoot rather than overshoot
        this.setTextSize(TypedValue.COMPLEX_UNIT_PX, lo);
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec)
    {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        int parentWidth = MeasureSpec.getSize(widthMeasureSpec);
        int height = getMeasuredHeight();
        refitText(this.getText().toString(), parentWidth);
        this.setMeasuredDimension(parentWidth, height);
    }

    @Override
    protected void onTextChanged(final CharSequence text, final int start, final int before, final int after) {
        refitText(text.toString(), this.getWidth());
    }

    @Override
    protected void onSizeChanged (int w, int h, int oldw, int oldh) {
        if (w != oldw) {
            refitText(this.getText().toString(), w);
        }
    }

    //Attributes
    private Paint mTestPaint;
}`

答案 1 :(得分:0)

尝试为您尝试在布局&amp;上设置值的userID设置标记。从你正在捕获点击的标签中获取id。在getView方法中,您可以执行此操作。在这种情况下无需收集项目位置,您可以直接获取项目ID。有关详细信息,请参阅代码。我希望这可以帮到你。

@Override
public View getView(int position, View convertView, ViewGroup parent) {  
try {  
if (convertView == null) {  
    LayoutInflater inflater = ((Activity) mContext).getLayoutInflater();  
    convertView = inflater.inflate(mLayoutResourceId, parent, false);  
}  
ShareWithArticle department = getItem(position);  
final TextView name = (TextView) convertView.findViewById(R.id.textView2);  
final TextView userId = (TextView) convertView.findViewById(R.id.textView3);  
name.setText(department.getUsrCompNm());  
userId.setText(department.getUsrID() + "");  
userId.setTag("set your key here like layout id", department.getUsrID());  
convertView.setOnClickListener(new View.OnClickListener() {  
@Override  
public void onClick(View v) {  
    String userNm  =   name.getText().toString();  
    String userIdtxt = userId.getText().toString();  
    // userNm how to pass values shareFragment  
    //userIdtxt how to pass values shareFragment  
}});  
} catch (Exception e) {  
    e.printStackTrace();  
}  
return convertView;  

}

答案 2 :(得分:0)

您需要在适配器类中添加这样的方法

public ShareWithArticle getItemAt(int position) {
    mDepartments.get(position);
}

现在

To.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                        @Override
                        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                               ShareWithArticle sa=adapter.getItemAt(position); 

                        }
                    });

希望它能帮到你

或者

To.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                        @Override
                        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
ShareWithArticle sa=(ShareWithArticle)adapter.getItem(position); 
                        }
                    });