Как масштабировать активность, чтобы точно соответствовать количеству изображений без места - PullRequest
0 голосов
/ 02 сентября 2018

У меня очень странная проблема. Здесь у меня есть всего 8 изображений в стиле Gridview, где каждое изображение имеет размер 392 × 500. Но когда я запускаю приложение, под последним восьмым изображением всегда остается небольшое пространство.

Вот мой код

public class BooksPage extends AppCompatActivity
        implements NavigationView.OnNavigationItemSelectedListener {


    int images[] = {R.drawable.phy,R.drawable.chem,R.drawable.drawable_logy,R.drawable.drawable_geology,R.drawable.bbs,R.drawable.drawable_chartered,R.drawable.bachelor,R.drawable.bachelor};

    String stream[]= {"MSC Physics","MSC Chemistry","MSC Biology",
            "MSC Geology","BBS|BBA","CA","Bachelor","+2 Science"};
    TextView navName,navEmail;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_books_page);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        getSupportActionBar().setTitle("पुस्तक किनबेच");

        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
                this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
        drawer.setDrawerListener(toggle);
        toggle.syncState();

        NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
        View navHeaderView = navigationView.getHeaderView(0);
        navName = (TextView)navHeaderView.findViewById(R.id.nav_name);
        navEmail = (TextView)navHeaderView.findViewById(R.id.nav_mail);

        navigationView.setNavigationItemSelectedListener(this);

        RecyclerView favPlaces = (RecyclerView) findViewById(R.id.favPlaces);
        StaggeredGridLayoutManager layoutManager = new StaggeredGridLayoutManager(2,StaggeredGridLayoutManager.VERTICAL);
        layoutManager.setGapStrategy(StaggeredGridLayoutManager.GAP_HANDLING_NONE);
        favPlaces.setLayoutManager(layoutManager);
        favPlaces.setHasFixedSize(true);
        ArrayList<BookDetails> placeList = getPlaces();

        if (!isNetworkStatusAvialable(this)) {


            Toast.makeText(this, "No Internet!", Toast.LENGTH_SHORT).show();



        }

        StaggeredAdapter staggeredAdapter = new StaggeredAdapter(this,placeList);
        favPlaces.setAdapter(staggeredAdapter);
        navName.setText(PreferenceManager.getDefaultSharedPreferences(this).getString("name","null"));
        navEmail.setText(PreferenceManager.getDefaultSharedPreferences(this).getString("email","null"));
    }
    private ArrayList<BookDetails> getPlaces() {
        ArrayList<BookDetails> details = new ArrayList<>();
        for (int index=0; index<images.length;index++){
            details.add(new BookDetails(images[index],stream[index]));
        }
        return details;
    }

   

}

Мой 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"
    xmlns:tools="http://schemas.android.com/tools"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="wrap_content">

    <android.support.v7.widget.CardView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        app:cardUseCompatPadding="true"
        app:cardCornerRadius="4dp">
        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:orientation="vertical"
            android:background="@color/colorPrimaryDark">

            <ImageView
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:id="@+id/placePic"
                android:adjustViewBounds="true"
                android:scaleType="fitXY" />

            <TextView
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:id="@+id/placeName"
                android:textStyle="bold"
                android:textColor="#ffffff"
                android:fontFamily="sans-serif-condensed"
                android:textAppearance="@style/Base.TextAppearance.AppCompat.Large"
                android:gravity="center"
                android:textSize="16sp"/>


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

</LinearLayout>

Тогда я, может быть, увеличу размер изображений, но добьюсь ли я размера изображения 50 × 50 или 1000 × 1000, размер изображения всегда будет одинаковым, а пространство постоянным.

Вот скриншот enter image description here

и снова то же самое с другим изображением [! [введите описание изображения здесь] [2]] [2]

Но забавно то, что я использую одно и то же изображение 7-го зелья и в 8-й позиции ..... Тогда пробелы в кадре и образы точно совпадают.

Вот скриншот enter image description here

в чем здесь проблема? Как я могу это исправить любая помощь приветствуется

Я использую Photoshop, чтобы изменить ширину и высоту моих изображений, сохраняя для Web.

1 Ответ

0 голосов
/ 02 сентября 2018

Приведенный ниже код решит проблему. Но может потребовать небольшого редактирования.

Добавьте приведенный ниже код в ваш fragment / Activity onCreate / ocreateView. Здесь вам нужен только декоратор предмета для вашего переработчика, чтобы масштабировать предмет

 mRecycler.addItemDecoration(new GridSpacingItemDecoration(2, dpToPx(2), true));

Добавить метод создания dpToPx

 /**
     * Converting dp to pixel
     */
    private int dpToPx(int dp) {
        Resources r = getResources();
        return Math.round(TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dp, r.getDisplayMetrics()));
    }

Теперь создайте класс для GridSpacingItemDecoration внутри вашей деятельности / фрагмента

 /**
     * RecyclerView item decoration - give equal margin around grid item
     */
    public class GridSpacingItemDecoration extends RecyclerView.ItemDecoration {

        private int spanCount;
        private int spacing;
        private boolean includeEdge;

        GridSpacingItemDecoration(int spanCount, int spacing, boolean includeEdge) {
            this.spanCount = spanCount;
            this.spacing = spacing;
            this.includeEdge = includeEdge;
        }

        @Override
        public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) {
            int position = parent.getChildAdapterPosition(view); // item position
            int column = position % spanCount; // item column

            if (includeEdge) {
                outRect.left = spacing - column * spacing / spanCount; // spacing - column * ((1f / spanCount) * spacing)
                outRect.right = (column + 1) * spacing / spanCount; // (column + 1) * ((1f / spanCount) * spacing)

                if (position < spanCount) { // top edge
                    outRect.top = spacing;
                }
                outRect.bottom = spacing; // item bottom
            } else {
                outRect.left = column * spacing / spanCount; // column * ((1f / spanCount) * spacing)
                outRect.right = spacing - (column + 1) * spacing / spanCount; // spacing - (column + 1) * ((1f /    spanCount) * spacing)
                if (position >= spanCount) {
                    outRect.top = spacing; // item top
                }
            }
        }
    }
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...