RecyclerView.Adapter中的按钮无法正常工作

时间:2016-04-05 09:53:34

标签: android android-recyclerview recycler-adapter

我正在开发一个应用程序,它允许我创建用户帐户并搜索我的数据库中的其他用户,以便“熟悉”他们。搜索的用户在RecyclerView中的CardView中可见。如果用户尚未作为朋友连接到我的帐户,则应该在卡上显示“添加好友”按钮。如果用户与我的帐户以朋友身份连接,则卡上的添加好友按钮不应该是可见的。根据是否可以添加此人,将一个int值发送到Adapter类,描述是否显示该按钮。问题是它不会立即起作用。如果我搜索某人如何已经是朋友,该按钮将不会出现。如果我然后搜索不是朋友的人,则该按钮不会在第一时间出现。我将不得不再次搜索用户以使按钮可见。反过来也是这样。

我可以得到任何帮助。感谢??

卡的XML布局

<pre><code>
<?xml version="1.0" encoding="utf-8"?>

<LinearLayout
    android:layout_height="match_parent"
    android:layout_width="match_parent"
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:card_view="http://schemas.android.com/apk/res-auto">

    <android.support.v7.widget.CardView
        xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:card_view="http://schemas.android.com/apk/res-auto"
        android:id="@+id/cv"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="16dp"
        android:background="@color/colorPrimary"
        card_view:cardCornerRadius="10dp"
        card_view:cardElevation="2dp">

        <RelativeLayout
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:background="@color/colorPrimary"
            android:padding="16dp"
            android:paddingBottom="16dp">

            <ImageView
                android:id="@+id/search_person_photo"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_alignParentStart="true"
                android:layout_alignParentTop="true"
                android:layout_marginEnd="16dp"
                android:contentDescription="@string/contentDescr_searchImage" />

            <TextView
                android:id="@+id/search_person_name"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_alignParentTop="true"
                android:layout_toEndOf="@+id/search_person_photo"
                android:textColor="@color/white"
                android:textSize="40sp" />

            <TextView
                android:id="@+id/search_person_email"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_below="@+id/search_person_name"
                android:layout_toEndOf="@+id/search_person_photo"
                android:textColor="@color/colorPrimaryDark"
                android:textSize="20sp" />

            <TextView
                android:id="@+id/search_person_username"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_below="@+id/search_person_email"
                android:layout_toEndOf="@+id/search_person_photo"
                android:textColor="@color/colorPrimaryDark"
                android:textSize="20sp" />

            <Button
                android:id="@+id/addFriendButton"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_alignParentEnd="true"
                android:layout_below="@+id/search_person_email"
                android:layout_marginBottom="16dp"
                android:background="@drawable/btn_default"
                android:text="@string/addFriendButton"
                android:textColor="@color/colorPrimary"/>

        </RelativeLayout>
    </android.support.v7.widget.CardView>
</LinearLayout>

</pre></code>

Card.java

<pre><code>
public class Card {

    public Card (String name, String email, String username) {
        this.name = name;
        this.email = email;
        this.username = username;

    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getEmail() {
        return email;
    }

    public void setEmail (String email) {
        this.email = email;
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }
}

</pre></code>

**AddFriendActivity**
<pre><code>
public class AddFriendActivity extends AppCompatActivity {

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

        db = new SQLiteHandler(getApplicationContext());
        search = (EditText) findViewById(R.id.inputSearch);
        pDialog = new ProgressDialog(this);
        pDialog.setCancelable(false);
        context = this;
        searchButton = (Button) findViewById(R.id.searchButton);
        toolbar = (Toolbar) findViewById(R.id.tool_bar);
        setSupportActionBar(toolbar);
        title = "Add Friend";
        getSupportActionBar().setTitle(title);
        if (getSupportActionBar() != null) {
            getSupportActionBar().setDisplayHomeAsUpEnabled(true);
            getSupportActionBar().setDisplayShowHomeEnabled(true);
        }

        // Fetching current user details from sqlite
        currentUser = db.getUserDetails();
        currentUserUsername = currentUser.get("user_name").toString();
        currentUserEmail = currentUser.get("email").toString();


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

                searchString = search.getText().toString();
                searchUser(searchString);

            }
        });


    }

    private void searchUser(final String username) {
        // Tag used to cancel the request
        String tag_string_req = "req_search";

        pDialog.setMessage("Searching User");
        pDialog.show();

        StringRequest strReq = new StringRequest(Request.Method.POST,
                AppConfig.URL_SEARCH_USER, new Response.Listener<String>() {

            @Override
            public void onResponse(String response) {
                Log.d(TAG, "Search Response: " + response.toString());
                pDialog.hide();

                try {
                    JSONObject jObj = new JSONObject(response);
                    boolean error = jObj.getBoolean("error");

                    // Check for error node in json
                    if (!error) {
                        //get User details from Json Response
                        JSONObject user = jObj.getJSONObject("user");
                        String JOBname = user.getString("name");
                        String JOBemail = user.getString("email");
                        String JOBusername = user.getString("user_name");

                        //add user details to cardView
                        List<Card> friendRequests = new ArrayList<Card>();
                        Card requestCard = new Card(JOBname, JOBemail, JOBusername);
                        friendRequests.add(requestCard);
                        //check if user isnt already a friend or our own self
                        friendshipExists(currentUserUsername, JOBusername);

                        RecyclerView recyclerView = (RecyclerView) findViewById(R.id.recyclerView);
                        UnscrollableLayoutManager layoutManager = new UnscrollableLayoutManager
                                (AddFriendActivity.this);
                        recyclerView.setLayoutManager(layoutManager);


                        SearchCardAdapter adapter = new SearchCardAdapter(friendRequests,
                                currentUserUsername, AddFriendActivity.this, canAdd);
                        recyclerView.setItemAnimator(new DefaultItemAnimator());
                        recyclerView.setAdapter(adapter);


                    } else {
                        // Error in login. Get the error message
                        String errorMsg = jObj.getString("error_msg");
                        Log.i(TAG, errorMsg);
                        Toast.makeText(getApplicationContext(),
                                errorMsg, Toast.LENGTH_LONG).show();
                    }
                } catch (JSONException e) {
                    // JSON error
                    e.printStackTrace();
                    Toast.makeText(getApplicationContext(), "Json error: " + e.getMessage(),
                            Toast.LENGTH_LONG).show();
                }

            }
        }, new Response.ErrorListener() {

            @Override
            public void onErrorResponse(VolleyError error) {
                Log.e(TAG, "Search Error: " + error.getMessage());
                Toast.makeText(getApplicationContext(),
                        error.getMessage(), Toast.LENGTH_LONG).show();
                pDialog.hide();
            }
        }) {

            @Override
            protected Map<String, String> getParams() {
                // Posting parameters to login url
                Map<String, String> params = new HashMap<String, String>();
                params.put("user_name", username);

                return params;
            }

        };

        // Adding request to request queue
        AppController.getInstance().addToRequestQueue(strReq, tag_string_req);
    }


    private void friendshipExists(final String currentUser, final String friendToAdd) {
        String tag_string_req = "req_checkFriendship";



        StringRequest strReq = new StringRequest(Request.Method.POST,
                AppConfig.URL_CHECK_FRIENDSHIP, new Response.Listener<String>() {

            @Override
            public void onResponse(String response) {


                try {
                    JSONObject jObj = new JSONObject(response);
                    boolean error = jObj.getBoolean("error");
                    Log.i(TAG, "Friendship response: " + String.valueOf(error));

                    if (error) {
                        canAdd = 0; //0 means we cannot add searched person, button shouldnt be visible
                    } else {
                        canAdd = 1; // we can add, button should be visible
                    }

                } catch (JSONException e) {
                    // JSON error
                    e.printStackTrace();
                    Toast.makeText(context, "Json error: " + e.getMessage(),
                            Toast.LENGTH_LONG).show();
                    Log.d(TAG, "Friendship Error: " + e.getMessage());
                }

            }
        }, new Response.ErrorListener() {

            @Override
            public void onErrorResponse(VolleyError error) {
                Log.e(TAG, "Error: " + error.getMessage());
                Toast.makeText(context,
                        error.getMessage(), Toast.LENGTH_LONG).show();
                Log.i(TAG, "Friendship Error: " + error.getMessage());

            }
        }) {

            @Override
            protected Map<String, String> getParams() {
                // Posting parameters to login url
                Map<String, String> params = new HashMap<String, String>();
                params.put("friend_one", currentUser);
                params.put("friend_two", friendToAdd);
                return params;
            }
        };

        // Adding request to request queue
        AppController.getInstance().addToRequestQueue(strReq, tag_string_req);
    }

}
</pre></code>

SearchCardAdapter

<pre><code>
public class SearchCardAdapter extends RecyclerView.Adapter<SearchCardAdapter.ViewHolder> {



    public SearchCardAdapter(List<Card> searchResult, String currentUserUsername,
                             Context context, int canAdd) {
        this.searchResult = searchResult;
        this.context = context;
        this.currentUserUsername = currentUserUsername;
        this.canAdd = canAdd;

    }

    @Override
    public SearchCardAdapter.ViewHolder onCreateViewHolder(final ViewGroup parent,
                                                           final int viewType) {

        final View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.search_card_view,
                parent, false);
        final ViewHolder viewHolder = new ViewHolder(view);
        pDialog = new ProgressDialog(parent.getContext());
        pDialog.setCancelable(false);

        return viewHolder;
    }


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

        holder.textViewName.setText(searchResult.get(position).getName());
        holder.textViewEmail.setText(searchResult.get(position).getEmail());
        holder.textViewUsername.setText(searchResult.get(position).getUsername());
        friendToAddUsername = searchResult.get(position).getUsername();

        if (canAdd == 0) {
            sendRequestButton.setVisibility(View.INVISIBLE);
        } else {
            sendRequestButton.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {

                    sendRequest(currentUserUsername, friendToAddUsername);
                }
            });
        }

    }

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

    public class ViewHolder extends RecyclerView.ViewHolder {

        private TextView textViewName;
        private TextView textViewEmail;
        private TextView textViewUsername;
        //private Button sendRequestButton;
        private CardView cardView;

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

            cardView = (CardView) itemView.findViewById(R.id.cv);
            textViewName = (TextView) itemView.findViewById(R.id.search_person_name);
            textViewEmail = (TextView) itemView.findViewById(R.id.search_person_email);
            textViewUsername = (TextView) itemView.findViewById(R.id.search_person_username);
            sendRequestButton = (Button) itemView.findViewById(R.id.addFriendButton);
        }
    }

    private void sendRequest(final String currentUser, final String friendToAdd) {
        String tag_string_req = "req_sendRequest";
        final String status = "0";

        pDialog.setMessage("Sending Friend Request");
        pDialog.show();

        StringRequest strReq = new StringRequest(Request.Method.POST,
                AppConfig.URL_SEND_FRIEND_REQUEST, new Response.Listener<String>() {

            @Override
            public void onResponse(String response) {
                Log.d(TAG, "Friend Request Response: " + response.toString());
                pDialog.hide();

                try {
                    JSONObject jObj = new JSONObject(response);
                    boolean error = jObj.getBoolean("error");

                    // Check for error node in json
                    if (!error) {
                        Toast.makeText(context,
                                "Friend request sent!", Toast.LENGTH_LONG).show();

                    } else {
                        // Error in login. Get the error message
                        String errorMsg = jObj.getString("error_msg");
                        Toast.makeText(context,
                                errorMsg, Toast.LENGTH_LONG).show();
                    }
                } catch (JSONException e) {
                    // JSON error
                    e.printStackTrace();
                    Toast.makeText(context, "Json error: " + e.getMessage(),
                            Toast.LENGTH_LONG).show();
                }

            }
        }, new Response.ErrorListener() {

            @Override
            public void onErrorResponse(VolleyError error) {
                Log.e(TAG, "Friend Request Error: " + error.getMessage());
                Toast.makeText(context,
                        error.getMessage(), Toast.LENGTH_LONG).show();
                pDialog.hide();
            }
        }) {

            @Override
            protected Map<String, String> getParams() {
                // Posting parameters to login url
                Map<String, String> params = new HashMap<String, String>();
                params.put("friend_one", currentUser);
                params.put("friend_two", friendToAdd);
                params.put("status", status);

                return params;
            }

        };

        // Adding request to request queue
        AppController.getInstance().addToRequestQueue(strReq, tag_string_req);
    }
}
</pre></code>

1 个答案:

答案 0 :(得分:0)

在按钮标记内添加以下行。

android:focusable="false"