Android RecyclerView片段中的项目宽度

问题描述 投票:0回答:1

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

@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中看到的那样,当项目数量超过视图时,高度项目宽度将获得图像3中的wrap_content而不是match_parent(图像2是它应该是正确的),因为您在滚动后可以看到,重新实例化的项目获得正确的宽度。我希望你明白这一点。

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

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

            }


        }
    }
}
java android android-recyclerview fragment
1个回答
0
投票

经过如此多的编辑和体验后,我发现我的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_behavior并将ContraintLayout更改为某些Linear或RelativeLayout问题后,现在已经不存在了。

我不知道为什么这部分会引起这样的问题,但这绝对是一个原因。

© www.soinside.com 2019 - 2024. All rights reserved.