代码之家  ›  专栏  ›  技术社区  ›  Ali Ahrabi

Android RecyclerView片段中的项目宽度

  •  0
  • Ali Ahrabi  · 技术社区  · 7 年前

    我有一个 RecyclerView 在一个 Fragment . 问题是,当项目计数超过视图高度时,视图中的每个项目都将获得最大宽度的内容(我的意思是所有项目都将获得最大宽度的包裹内容)。在图像中,更具体的是,在滚动那些将刷新的视图后,其宽度将正确(匹配父视图)。我已经在其他问题上尝试了这些代码建议,但问题仍然存在。这是我的代码:

    @Override
    public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View itemView = LayoutInflater.from(parent.getContext())
                .inflate(R.layout.complex_item, parent, false);
    
        return new ViewHolder(itemView);
    }
    

    项目的xml布局:

    <?xml version="1.0" encoding="utf-8"?>
    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:app="http://schemas.android.com/apk/res-auto"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_margin="5dp"
        android:id="@+id/baseBg"
        android:orientation="vertical">
    
        <LinearLayout
            android:id="@+id/expand_button"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:background="@drawable/list_item_background"
            android:foreground="?selectableItemBackground"
            android:gravity="center|right"
            android:orientation="vertical"
            android:padding="10dp">
    
            <TextView
                android:id="@+id/textViewTitle"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_margin="10dp"
                android:textColor="@color/colorPage5"
                android:textSize="20sp"
                android:textStyle="bold" />
        </LinearLayout>
    </LinearLayout>
    

    片段替换的代码段:

    mainPageFrameLayout.removeAllViews();
    FragmentTransaction ft = 
    getSupportFragmentManager().beginTransaction();
    ft.replace(R.id.mainPageFrameLayout, new MojtamaFragment(id, "3"));
    ft.commit();
    

    以及 mainPageFrameLayout :

    <FrameLayout
        android:id="@+id/mainPageFrameLayout"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="1"
        android:animateLayoutChanges="true"
        android:background="@color/colorPage5" />
    

    适配器和 onCreateView :

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View rootView = inflater.inflate(R.layout.recycler_view_fragment, container, false);
    
        final RecyclerView recyclerView = rootView.findViewById(R.id.recycler_view);
        recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
        ...
        //(this part items is getting generated by a Http Request)
        ...
        recyclerView.setAdapter(new SimpleAdapter(recyclerView, id, title, getActivity(), complexID,MojtamaFragment.this));
        return rootView;
    }
    

    图像:

    enter image description here

    enter image description here

    enter image description here

    编辑:图像解释:如图1所示,当项目编号超过视图高度项目宽度得到wrap\u内容,而不是match\u父项(图2是正确的,应该是)时,如图3所示,在我滚动后所示,重新实例化的项目得到正确的宽度。我希望你明白我的意思。

    编辑3:这是整个适配器和viewholder代码和导入:

    package com.ahrabi.ojekavir.Fragments;
    
    import android.annotation.SuppressLint;
    import android.content.Context;
    import android.content.SharedPreferences;
    import android.graphics.drawable.BitmapDrawable;
    import android.os.Bundle;
    import android.preference.PreferenceManager;
    import android.support.annotation.NonNull;
    import android.support.annotation.Nullable;
    import android.support.v4.app.Fragment;
    import android.support.v7.widget.LinearLayoutManager;
    import android.support.v7.widget.RecyclerView;
    import android.util.Log;
    import android.view.Gravity;
    import android.view.LayoutInflater;
    import android.view.View;
    import android.view.ViewGroup;
    import android.widget.EditText;
    import android.widget.LinearLayout;
    import android.widget.PopupWindow;
    import android.widget.TextView;
    import android.widget.Toast;
    
    import com.ahrabi.ojekavir.R;
    import com.ahrabi.ojekavir.connector.HttpVolley;
    
    import org.json.JSONArray;
    import org.json.JSONException;
    import org.json.JSONObject;
    
    /**
     * Created by Ahrabi2 on 1/10/2018.
     */
    
    @SuppressLint("ValidFragment")
    public class MojtamaFragment extends Fragment {
    
        public static final String GET_COMPLEX_LIST_URL = "/Building/getComplexList";
        public static final String LOGIN_URL = "/user/Login";
    
        SharedPreferences prefs;
        public String firsturl;
        private String[] id, title;
        private String idCame, complexID;
    
        @SuppressLint("ValidFragment")
        public MojtamaFragment(String id, String complexID) {
            this.idCame = id;
            this.complexID = complexID;
        }
    
        @Nullable
        @Override
        public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
            View rootView = inflater.inflate(R.layout.recycler_view_fragment, container, false);
    
            final RecyclerView recyclerView = rootView.findViewById(R.id.recycler_view);
            recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
    
    
            prefs = PreferenceManager.getDefaultSharedPreferences(getActivity());
            if (prefs.getBoolean("net_switch", false)) {
                // Your switch is on
                Log.v("Requests", "Over Network");
                firsturl = prefs.getString("internet_url", getResources().getString(R.string.pref_default_display_internet));
                Log.v("Over internet url", firsturl);
            } else {
                // Your switch is off
                Log.v("Requests", "Over Local");
                firsturl = prefs.getString("local_url", getResources().getString(R.string.pref_default_display_local));
                Log.v("Local url", firsturl);
            }
            String[] keys = new String[2];
            String[] values = new String[2];
    
            keys[0] = "ComplexTypeId";
            keys[1] = "regionID";
    
            values[0] = complexID;
            values[1] = idCame;
    
    
            new HttpVolley
                    ().HttpVolleyPost(getActivity(), firsturl + GET_COMPLEX_LIST_URL, keys, values, new HttpVolley.VolleyResponseListener() {
                @Override
                public void onError(String message) {
    
    
                }
    
                @Override
                public void onResponse(String response) {
                    if (response.contentEquals("-7")) {
    
                    } else {
    //                        response = response.replaceAll("\\", "");
                        Log.v("Response", response);
                        String jsonResult = "{" + "\"" + "android" + "\"" + ":" + response
                                + "}";
                        try {
    
                            JSONObject jObject = new JSONObject(jsonResult);
    
                            // Getting JSON Array from URL
                            JSONArray android = jObject.getJSONArray("android");
                            Log.v("android", android.toString());
                            Log.v("android.length()", "" + android.length());
                            id = new String[android.length()];
                            title = new String[android.length()];
                            for (int i = 0; i < android.length(); i++) {
                                JSONObject c = android.getJSONObject(i);
                                // Storing JSON item in a Variable
                                id[i] = c.getString("id");
                                title[i] = c.getString("Name");
                            }
                            recyclerView.setAdapter(new SimpleAdapter(recyclerView, id, title, getActivity(), complexID,MojtamaFragment.this));
    
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                }
    
            });
            return rootView;
        }
    
        private void showLoginPopup(String page) {
            LayoutInflater curInflate = (LayoutInflater) getActivity()
                    .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            final View curLayout = curInflate.inflate(R.layout.login_popup,
                    (ViewGroup) getActivity().findViewById(R.id.mainLinearPopup));
    
            final PopupWindow swindo = new PopupWindow(curLayout,
                    ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT, true);
            swindo.setBackgroundDrawable(new BitmapDrawable());
    
            swindo.setFocusable(true);
    //      swindo.setAnimationStyle(R.style.PopupWindowAnimation);
            swindo.showAtLocation(curLayout, Gravity.BOTTOM,
                    ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
    
            LinearLayout bg = (LinearLayout) curLayout
                    .findViewById(R.id.bgLinearPopup);
            LinearLayout loginIV = (LinearLayout) curLayout
                    .findViewById(R.id.loginIV);
            final EditText loginUserName = (EditText) curLayout
                    .findViewById(R.id.loginUserName);
            final EditText loginPassword = (EditText) curLayout
                    .findViewById(R.id.loginPassword);
            if (page.contentEquals("1"))
                loginIV.setBackgroundResource(R.drawable.item_brown_bg);
            else if (page.contentEquals("3"))
                loginIV.setBackgroundResource(R.drawable.item_orange_bg);
            bg.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    swindo.dismiss();
                }
            });
            loginIV.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    if (loginUserName.getText().toString().contentEquals("")){
    
                    } else if (loginPassword.getText().toString().contentEquals("")){
                    } else {
                        String[] keys = new String[2];
                        String[] values = new String[2];
    
                        keys[0] = "userName";
                        keys[1] = "password";
    
                        values[0] = loginUserName.getText().toString();
                        values[1] = loginPassword.getText().toString();
    
    
    
                        new HttpVolley
                                ().HttpVolleyPost(getActivity(), firsturl + LOGIN_URL, keys, values, new HttpVolley.VolleyResponseListener() {
                            @Override
                            public void onError(String message) {
    
    
                            }
    
                            @Override
                            public void onResponse(String response) {
                                if (response.contentEquals("1")) {
    
                                } else {
    
                                }
                            }
    
                        });
                    }
    
                }
            });
        }
        private static class SimpleAdapter extends RecyclerView.Adapter<SimpleAdapter.ViewHolder> {
    
    
            private RecyclerView recyclerView;
    
            private String[] id, title;
            private Context context;
            private String complexID;
            private MojtamaFragment mojtamaFragment;
            public SimpleAdapter(RecyclerView recyclerView, String[] id, String[] title, Context context, String complexID,MojtamaFragment mojtamaFragment) {
                this.recyclerView = recyclerView;
                this.id = id;
                this.title = title;
                this.context = context;
                this.complexID = complexID;
                this.mojtamaFragment = mojtamaFragment;
            }
    
            @Override
            public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
                View itemView = LayoutInflater.from(parent.getContext())
                        .inflate(R.layout.complex_item, parent, false);
    
                return new ViewHolder(itemView);
            }
    
            @Override
            public void onBindViewHolder(ViewHolder holder, int position) {
    
    
                holder.textViewTitle.setText(title[position]);
                if (complexID.contentEquals("1"))
                    holder.textViewTitle.setTextColor(context.getResources().getColor(R.color.colorPage6));
                else if (complexID.contentEquals("3"))
                    holder.textViewTitle.setTextColor(context.getResources().getColor(R.color.colorPage5));
            }
    
            @Override
            public int getItemCount() {
                return id.length;
            }
    
            public class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
    
                private TextView textViewTitle;
                private LinearLayout expandButton;
    
                public ViewHolder(View itemView) {
                    super(itemView);
    
                    expandButton = itemView.findViewById(R.id.expand_button);
                    textViewTitle = itemView.findViewById(R.id.textViewTitle);
    
                    expandButton.setOnClickListener(this);
                }
    
    
                @Override
                public void onClick(View view) {
                    ViewHolder holder = (ViewHolder) recyclerView.findViewHolderForAdapterPosition(getAdapterPosition());
    
                    mojtamaFragment.showLoginPopup(complexID);
    
                }
    
    
            }
        }
    }
    
    1 回复  |  直到 7 年前
        1
  •  0
  •   Ali Ahrabi    7 年前

    经过这么多的编辑和体验,我发现xml布局中的一部分代码(FrameLayout在其中,片段被它替换)与错误有关:

    <android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:app="http://schemas.android.com/apk/res-auto"
        xmlns:tools="http://schemas.android.com/tools"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        app:layout_behavior="@string/appbar_scrolling_view_behavior"
        tools:context="com.ahrabi.ojekavir.CityActivity"
        tools:showIn="@layout/activity_city">
    

    在删除app:layout\u行为并将containtlaway更改为某些线性或相对性问题之后,现在就不存在了。

    我不知道为什么这部分会出现这样的问题,但这肯定是有原因的。