簡體   English   中英

RecyclerView.Adapter中的按鈕無法正常工作

[英]Button within RecyclerView.Adapter not working properly

我正在開發一個應用程序,該應用程序允許我創建用戶帳戶並在數據庫中搜索其他用戶,以便與他們“成為朋友”。 搜索到的用戶在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>

在您的按鈕標簽內添加以下行。

android:focusable="false"

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM