2016-03-04 52 views
0

的Android上setOnItemClickListener無法正常工作如何選擇的值獲得 顯示爲ShareWithArticle @ 211f2370機器人如何選擇setOnItemClickListener得到應有的價值選擇

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); 
    } 

} 
+0

你的適配器由 「ShareWithArticle」 類的對象。而不是「String selected = String.valueOf(adapter.getItem(position));」使用此--- --- ShareWithArticle shareObj =(ShareWithArticle)adapter.getItem(位置) –

+0

不工作請其他建議 –

+0

請修正問題 –

回答

0

嘗試爲用戶標識設置標籤,您正試圖在佈局上設置值&從捕獲點擊的標籤中獲取標識。在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; 

}

1
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; 
SharedFragment fragment; 
    public CustomerAdapter(Context context, int resource, List<ShareWithArticle> departments,SharedFragment fragment) { 
     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<>(); 

     this.fragment = fragment; 
    } 

    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 Listener(name,userId)); 

     } catch (Exception e) { 
      e.printStackTrace(); 
     } 
     return convertView; 
    } 
class Listener implements View.OnClickListener 
    { 
    TextView name; 
    TextView userId; 

    Listener(TextView name, TextView userId) 
    { 
    this.name = name; 
    this.userId = userId; 

    } 

    @Override 
     public void onClick(View v) { 

          String userNm = name.getText().toString(); 
        String userIdtxt = userId.getText().toString(); 

        //create a method in fragment class and pass the data using tthe object. 

       fragment.setData(userNm,userIdtxt); 

     } 
    } 
    @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(); 
      } 
     }; 
    } 

} 
+0

fragment.setData(userNm,userIdtxt);如何使用 –

+0

在ShowFragment類 –

+0

中創建方法,並在適配器中傳遞相同的片段對象也 –

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); 
         } 
        });