简体   繁体   English

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

[英]Button within RecyclerView.Adapter not working properly

I'm working on an application that allows me to create user accounts and search for other users in my database in order to "friend" them. 我正在开发一个应用程序,该应用程序允许我创建用户帐户并在数据库中搜索其他用户,以便与他们“成为朋友”。 The user searched is visible in a CardView within a RecyclerView. 搜索到的用户在RecyclerView的CardView中可见。 If the user isn't already connected to my account as a friend, an Add Friend button is supposed to be visible on the card. 如果该用户尚未作为朋友连接到我的帐户,则该卡上应该显示“添加朋友”按钮。 If the user is connected with my account as friend, then the add friend button on the card is not supposed to be visible. 如果用户作为朋友与我的帐户建立了联系,则该卡上的“添加朋友”按钮将不可见。 Depending on whether the person can be added or not, an int value is sent to Adapter class depicting whether to show the button or not. 根据是否可以添加此人,会将int值发送到Adapter类,以描述是否显示按钮。 The problem is that it's doesnt work immediately. 问题是它不能立即工作。 If i search for someone how is already a friend, the button wont show up. 如果我搜索某人已经是朋友,该按钮将不会显示。 If i then search for someone who isn't a friend the button wont show up the first time. 如果我然后搜索不是朋友的人,该按钮将不会在第一时间显示。 I'll have to search for the user again for the button to be visible. 我将不得不再次搜索用户以使按钮可见。 It's the same the other way around. 反之亦然。

Can I get any help on this please. 请给我任何帮助。 Thanks?? 谢谢??

XML Layout for the card 卡的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 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 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>

在您的按钮标签内添加以下行。

android:focusable="false"

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM