Gridview项目自动调整问题?

时间:2017-04-15 07:33:42

标签: android android-layout gridview

enter image description here

我在滚动视图中使用了两个可扩展的高度网格视图。我面临这个问题。当在文本视图中设置动态文本时,网格视图显示如下图像。如何解决此问题?。在textview中设置静态文本时查看perfect.but使用动态我有一个问题。我可以解决它吗?

我的布局代码:

<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.CardView 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="match_parent"
    android:orientation="vertical"
    android:layout_margin="@dimen/SIZE_5"
    >

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical"
        android:weightSum="1"
        >

    <ImageView
        android:id="@+id/iv_sub_categories_img"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="0.9"
        android:layout_gravity="center"

        android:gravity="center"
        android:src="@drawable/download"
        android:contentDescription="@null" />


    <TextView
        android:id="@+id/tv_sub_categories_name"
        style="@android:style/TextAppearance.Small"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="0.1"
        android:padding="@dimen/SIZE_5"
        android:layout_gravity="center"
        android:gravity="center"

        android:text="hello world"

        />


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

我的java代码:

public class MyFragment extends Fragment implements View.OnClickListener {
    private AQuery mAQuery;
    private TransparentProgressDialog mTransparentProgressDialog;
    private ExpandableHeightGridView mGridViewCategory, mGridViewProdcuts;
    private CustomTextView mTvNoData;
    private ArrayList<HomeSubCategoriesData> mArrayList;
    private ArrayList<HomeSubProductsData> mArrayProductsList;
    private String mSubCategoryGetDetails = "";
    private TextView mTvTitle, mTvBack, mTvProductTitle;
    private ScrollView mLinear;
    public MyFragment() {
        // Required empty public constructor
    }
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View v = inflater.inflate(R.layout.fragment_seller_sub_category, container, false);
        initialization(v);
        return v;
    }
    private void initialization(View v) {
       /* MainActivity dashboard = (MainActivity) getActivity();
        mainDashbordInterface = dashboard.mainDashbordInterface;
        mainDashbordInterface.setListener();*/
        mAQuery = new AQuery(getActivity());
        mTransparentProgressDialog = new TransparentProgressDialog(getActivity(), R.drawable.ic_loader_image);
        mGridViewCategory = (ExpandableHeightGridView) v.findViewById(R.id.grid_fragment_sub_category);
        mGridViewProdcuts = (ExpandableHeightGridView) v.findViewById(R.id.grid_fragment_sub_products);
        mTvNoData = (CustomTextView) v.findViewById(R.id.tv_no_data_grid_home_sub_seller);
        mTvTitle = (TextView) v.findViewById(R.id.tv_sub_category_title);
        mTvProductTitle = (TextView) v.findViewById(R.id.tv_seller_sub_categories_product_title);
        mTvBack = (TextView) v.findViewById(R.id.tv_sub_category_back);
        mLinear = (ScrollView) v.findViewById(R.id.linear_seller_sub_category);
        mArrayList = new ArrayList<>();
        mArrayProductsList = new ArrayList<>();

        mTransparentProgressDialog.show();
        mLinear.setVisibility(View.INVISIBLE);
        //auto fit column items in grid view
      /*  float scaleFactor = getResources().getDisplayMetrics().density * 100;
        int number = getActivity().getWindowManager().getDefaultDisplay().getWidth();
        int columns = (int) ((float) number / (float)scaleFactor);
        mGridViewCategory.setNumColumns(columns);
        mGridViewProdcuts.setNumColumns(columns);*/
        getSubCategoriesData();
        mGridViewCategory.setExpanded(true);
        mGridViewProdcuts.setExpanded(true);
        //before change below line :  ajaxCallback.setTimeout(Integer.parseInt(getString(R.string.ajax_timeout)));
        AbstractAjaxCallback.setTimeout(Integer.parseInt(getString(R.string.ajax_timeout)));
        int newConfig = getActivity().getResources().getConfiguration().orientation;
        mGridViewCategory.setNumColumns(newConfig == Configuration.ORIENTATION_LANDSCAPE ? 4 : 3);
        mGridViewProdcuts.setNumColumns(newConfig == Configuration.ORIENTATION_LANDSCAPE ? 4 : 3);
        mTvBack.setOnClickListener(this);
    }
    private void getSubCategoriesData() {
        mSubCategoryGetDetails = getString(R.string.WS_HOST) + getString(R.string.WS_GET_CATEGORIES);
         //mSubCategoryGetDetails = "http://www.json-generator.com/api/json/get/ckJkJopOdK?indent=2";
       // mSubCategoryGetDetails = "http://www.json-generator.com/api/json/get/bSrFHjWEXS?indent=2";
        HashMap<String, Object> hashMap = new HashMap<>();
        hashMap.put("order_id", getActivity().getIntent().getStringExtra("key"));
        hashMap.put("seller_id", 266);
        hashMap.put("category_id", getArguments().getString("id"));
        Log.e("Categories list", "Hah map-->" + hashMap.toString());
        if (AvailableNetwork.isConnectingToInternet(getActivity())) {
            mAQuery./*progress(mTransparentProgressDialog).*/ajax(mSubCategoryGetDetails, hashMap, JSONObject.class, ajaxCallback);
        } else {
            //showAlert(getString(R.string.no_internt_connection), -1);
            Snackbar snackbar = Snackbar
                    .make(MainActivity.coordinatorLayout, R.string.no_internt_connection, Snackbar.LENGTH_LONG)
                    .setAction("RETRY", new View.OnClickListener() {
                        @Override
                        public void onClick(View view) {
                            //setUI(view);
                        }
                    });
            // Changing message text color
            snackbar.setActionTextColor(Color.RED);
            // Changing action button text color
            View sbView = snackbar.getView();
            CoordinatorLayout.LayoutParams params = (CoordinatorLayout.LayoutParams) sbView.getLayoutParams();
            params.gravity = Gravity.TOP;
            sbView.setLayoutParams(params);
            TextView textView = (TextView) sbView.findViewById(android.support.design.R.id.snackbar_text);
            textView.setTextColor(Color.YELLOW);
            snackbar.show();
            mTvNoData.setVisibility(View.VISIBLE);
        }
    }
    /*8SHow alert dialog box**/
    private void showAlert(String message, int flg) {
        AlertDialog.Builder aBuilder = new AlertDialog.Builder(getActivity());
        aBuilder.setCancelable(false);
        aBuilder.setMessage(message);
        aBuilder.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
            }
        });
        aBuilder.create();
        aBuilder.show();
    }
/*8Web service Rrespoce**/
    AjaxCallback<JSONObject> ajaxCallback = new AjaxCallback<JSONObject>() {
        @Override
        public void callback(String url, JSONObject object, AjaxStatus status) {
            super.callback(url, object, status);
            Log.e("buyer order", "url" + url);
            Log.e("Buyer order", "Responce" + object);
            if (status.getCode() == 200) {
                if (object != null) {
                    if (url.equalsIgnoreCase(mSubCategoryGetDetails)) {
                        try {
                            if (object.getString("errorcode").equalsIgnoreCase("0")) {
                                JSONObject jsonObject = object.getJSONObject("category");
                                JSONArray jsonArrayParent = jsonObject.getJSONArray("parentcategory");
                                Gson gson = new Gson();
                                mTvBack.setVisibility(View.VISIBLE);
                                for (int i = 0; i < jsonArrayParent.length(); i++) {
                                    JSONObject Object = jsonArrayParent.getJSONObject(i);
                                    mTvTitle.setText(Object.getString("name"));
                                    mTvProductTitle.setText(mTvTitle.getText().toString() + " Products");
                                    // mainDashbordInterface.setTitle(Object.getString("name"));
                                }
                                JSONArray jsonArray = jsonObject.getJSONArray("childcategory");
                                for (int i = 0; i < jsonArray.length(); i++) {
                                    JSONObject obj = jsonArray.getJSONObject(i);
                                    HomeSubCategoriesData subCategoriesModel = gson.fromJson(obj.toString(), HomeSubCategoriesData.class);
                                    mArrayList.add(subCategoriesModel);
                                }
                                JSONArray jsonArray1 = jsonObject.getJSONArray("productdetails");
                                mTvProductTitle.setVisibility(View.VISIBLE);
                                for (int i = 0; i < jsonArray1.length(); i++) {
                                    JSONObject obj = jsonArray1.getJSONObject(i);
                                    HomeSubProductsData subProductModel = gson.fromJson(obj.toString(), HomeSubProductsData.class);
                                    mArrayProductsList.add(subProductModel);
                                }
                            } else if (object.getString("errorcode").equalsIgnoreCase("1")) {
                                showAlert("No order details found.", -1);
                            } else if (object.getString("errorcode").equalsIgnoreCase("0")) {
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                        HorizontalSubCatAdapter adapter = new HorizontalSubCatAdapter(getActivity(), mArrayList);
                        mGridViewCategory.setAdapter(adapter);
                        HorizontalSubProductAdapter productAdapter = new HorizontalSubProductAdapter(getActivity(), mArrayProductsList);
                        mGridViewProdcuts.setAdapter(adapter);
                        new Handler().postDelayed(new Runnable() {
                            @Override
                            public void run() {
                                mLinear.setVisibility(View.VISIBLE);
                                mTransparentProgressDialog.dismiss();
                                Log.e("progress bar", "Hah map-->" + "progress bar called");
                            }
                        }, 3000);
                    }
                } else {
                    mTvNoData.setVisibility(View.VISIBLE);
                }
            }
        }
    };
    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        mGridViewCategory.setNumColumns(newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE ? 4 : 3);
        mGridViewProdcuts.setNumColumns(newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE ? 4 : 3);
       /* float scaleFactor = getResources().getDisplayMetrics().density * 100;
        int number = getActivity().getWindowManager().getDefaultDisplay().getWidth();
        int columns = (int) ((float) number / (float)scaleFactor);
        mGridViewCategory.setNumColumns(columns);
        mGridViewProdcuts.setNumColumns(columns);*/
        super.onConfigurationChanged(newConfig);
    }
    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.tv_sub_category_back:
                getActivity().onBackPressed();
                mTvBack.setVisibility(View.GONE);
                break;
        }
    }
    @Override
    public void onResume() {
        super.onResume();
    }
}

我的Adapter类:

public class HorizontalSubCatAdapter extends BaseAdapter {
    private ArrayList<HomeSubCategoriesData> mArrayList;
    private Context mContext;
    private LayoutInflater mLayoutInflater;
    public HorizontalSubCatAdapter(FragmentActivity activity, ArrayList<HomeSubCategoriesData> mArrayList) {
        this.mContext = activity;
        this.mArrayList = mArrayList;
        mLayoutInflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    }
    @Override
    public int getCount() {
        return mArrayList.size();
    }
    @Override
    public Object getItem(int position) {
        return mArrayList.get(position);
    }
    @Override
    public long getItemId(int position) {
        return position;
    }
    @Override
    public View getView(final int position, View convertView, ViewGroup parent) {
        ViewHolder mViewHolder;
        if (convertView == null) {
            mViewHolder = new ViewHolder();
            convertView = mLayoutInflater.inflate(R.layout.item_subcategories_list, parent,false);
            mViewHolder.mTvName = (TextView) convertView.findViewById(R.id.tv_sub_categories_name);
            mViewHolder.mIvimage = (ImageView) convertView.findViewById(R.id.iv_sub_categories_img);
            mViewHolder.mIvimage.setAdjustViewBounds(true);
            mViewHolder.mIvimage.setPadding(10,10,10,10);
            convertView.setFocusableInTouchMode(true);
            convertView.setTag(mViewHolder);
        } else {
            mViewHolder = (ViewHolder) convertView.getTag();
        }
        Picasso.with(mContext).load(mArrayList.get(position).getCat_img()).resize(300,300).into(mViewHolder.mIvimage);
            mViewHolder.mTvName.setText(mArrayList.get(position).getName());
        /*String img = "http://app.joinerytrade.com/media/catalog/product/cache/1/small_image/210x/9df78eab33525d08d6e5fb8d27136e95/4/0/400_1_door_01.jpg";
        Picasso.with(mContext).load(img).into(mViewHolder.mIvimage);*/
        convertView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
               // Toast.makeText(mContext, mArrayList.get(position).getName(), Toast.LENGTH_SHORT).show();
                //calling fragment from adatper class...
                SubCategoryProductsFragment fragment = new SubCategoryProductsFragment();
                FragmentManager fm = ((MainActivity) mContext).getSupportFragmentManager();
                Bundle bundle = new Bundle();
                bundle.putString("id", String.valueOf(mArrayList.get(position).getId()));
                fragment.setArguments(bundle);
                fm.beginTransaction().replace(R.id.content_frame, fragment).addToBackStack(null).commit();
            }
        });
        return convertView;
    }
    private class ViewHolder {
        TextView mTvName;
        ImageView mIvimage;
    }
}

1 个答案:

答案 0 :(得分:0)

使用这个:

<LinearLayout
    android:id="@+id/dashrowlin"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical">

    <ImageView
        android:id="@+id/dashImg"
        android:layout_width="60dp"
        android:layout_height="60dp"
        android:layout_gravity="center"
        android:layout_marginTop="15dp"
        />

    <TextView
        android:id="@+id/dashName"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:layout_marginTop="5dp"
        android:gravity="center"
        android:padding="7dp"
        android:maxLines="2"
        android:lines="2"
        android:ellipsize="end"
        android:textColor="@color/colorPrimary"
        android:textSize="14sp" />
</LinearLayout>