Android центрирует изображение программно

ОК, я безуспешно пытаюсь переработать советы, данные в этих сообщениях, о программном центрировании изображения. Мое приложение в основном работает и состоит из счетчика с изображением и нескольких TextView под ним. Их содержимое зависит от положения счетчика. Я бы хотел, чтобы изображение было выровнено по центру, когда счетчик находится в положении по умолчанию, и выровнено по левому краю, когда что-то было выбрано. Макеты определены в файлах макетов, один для портрета, а другой для ландшафта, и вот часть моего кода, с которой я борюсь: -

@Override
        public void onItemSelected(AdapterView<?> parent, View view,
                int position, long id) {

            // The variable index identifies the position the spinner is in.
            // TextView name, country and description... locks to the
            // TextViews defined in the activity_main.xml layout files.
            int index = parent.getSelectedItemPosition();
            TextView name = (TextView) findViewById(R.id.name);
            TextView country = (TextView) findViewById(R.id.country);
            TextView description = (TextView) findViewById(R.id.description);

            // Now we'll check to see if we're in the None Selected spinner
            // position. If true we'll dump the name, country and
            // description TextViews otherwise these will be shown.

            if (index == 0) {

                image.setImageResource(imgs.getResourceId(
                        spinner1.getSelectedItemPosition(), -1));
                // Try and centre the image when none is selected
                RelativeLayout.LayoutParams lp = (RelativeLayout.LayoutParams) image
                        .getLayoutParams();
                lp.addRule(RelativeLayout.CENTER_VERTICAL);
                image.setLayoutParams(lp);

                name.setVisibility(View.GONE);
                country.setVisibility(View.GONE);
                description.setVisibility(View.GONE);

            } else {

                image.setImageResource(imgs.getResourceId(
                        spinner1.getSelectedItemPosition(), -1));
                // Try and left align the image when the spinner is NOT in
                // the None Selected position.
                RelativeLayout.LayoutParams lp = (RelativeLayout.LayoutParams) image
                        .getLayoutParams();
                lp.addRule(RelativeLayout.ALIGN_PARENT_LEFT);
                image.setLayoutParams(lp);

                name.setVisibility(View.VISIBLE);
                country.setVisibility(View.VISIBLE);
                description.setVisibility(View.VISIBLE);

                name.setText(leaders[index]);
                country.setText(states[index]);
                description.setText(descrip[index]);
            }

        }

Вот фрагменты из моих файлов макета: Activity_main.xml книжная ориентация:

<ImageView
            android:id="@+id/leaderPhoto"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:contentDescription="@string/accessability"
            android:scaleType="centerInside"
            android:src="@drawable/ic_world1" />

Activity_in.xml альбомный вид:

<ImageView
            android:id="@+id/leaderPhoto"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:adjustViewBounds="false"
            android:contentDescription="@string/accessability"
            android:paddingLeft="8dp"
            android:scaleType="center"
            android:src="@drawable/ic_world1" />

person Roger W    schedule 23.12.2013    source источник


Ответы (3)


Попробуйте изменить RelativeLayout.CENTER_VERTICAL на RelativeLayout.CENTER_HORIZONTAL, если вы хотите, чтобы он центрировался по горизонтали, или на RelativeLayout.CENTER_IN_PARENT, чтобы центрировать его по обеим осям.

person Anup Cowkur    schedule 23.12.2013
comment
Спасибо, Ануп, CENTER_IN_PARENT, кажется, работает, когда приложение запускается впервые, но после выбора чего-то другого, кроме положения счетчика по умолчанию, а затем возврата к положению по умолчанию, это не так, то есть изображение начинает выравниваться по центру, когда приложение запускается, перемещается в выровнено по левому краю, когда что-то было выбрано, и остается выровненным по левому краю, когда вы возвращаетесь к позиции «Нет выбранных». - person Roger W; 23.12.2013
comment
это потому, что вы добавляете новое правило только при изменении индекса. Вы должны удалить старое правило, когда добавляете новое. См.: stackoverflow.com/a/5110767/1369222. - person Anup Cowkur; 23.12.2013
comment
Спасибо, Ануп, еще не решено, но вы дали мне полезную информацию. Понятно, что. - person Roger W; 23.12.2013

я внес некоторые изменения в ваш код, чтобы решить ваш вопрос и помочь вам:

@Override
        public void onItemSelected(AdapterView<?> parent, View view,
                int position, long id) {

            // The variable index identifies the position the spinner is in.
            // TextView name, country and description... locks to the
            // TextViews defined in the activity_main.xml layout files.
            int index = parent.getSelectedItemPosition();
            TextView name = (TextView) findViewById(R.id.name);
            TextView country = (TextView) findViewById(R.id.country);
            TextView description = (TextView) findViewById(R.id.description);

            // Now we'll check to see if we're in the None Selected spinner
            // position. If true we'll dump the name, country and
            // description TextViews otherwise these will be shown.

            if (index == 0) {

                image.setImageResource(imgs.getResourceId(
                        spinner1.getSelectedItemPosition(), -1));
                // Try and centre the image when none is selected
                RelativeLayout.LayoutParams lp = (RelativeLayout.LayoutParams) image
                        .getLayoutParams();
                lp.addRule(0);
                //this will make it center according to its parent
                lp.addRule(RelativeLayout.CENTER_IN_PARENT );

                image.setLayoutParams(lp);

                name.setVisibility(View.GONE);
                country.setVisibility(View.GONE);
                description.setVisibility(View.GONE);

            } else {

                image.setImageResource(imgs.getResourceId(
                        spinner1.getSelectedItemPosition(), -1));
                // Try and left align the image when the spinner is NOT in
                // the None Selected position.
                RelativeLayout.LayoutParams lp = (RelativeLayout.LayoutParams) image
                        .getLayoutParams();
                lp.addRule(0);
                lp.addRule(RelativeLayout.ALIGN_PARENT_LEFT);
                image.setLayoutParams(lp);

                name.setVisibility(View.VISIBLE);
                country.setVisibility(View.VISIBLE);
                description.setVisibility(View.VISIBLE);

                name.setText(leaders[index]);
                country.setText(states[index]);
                description.setText(descrip[index]);
            }

        }

обновление: по словам Анупа Цовкура, вы должны использовать его так, как показано в моем обновленном коде: я надеюсь, что ваша проблема решена :)

ваше здоровье,

Хамад

person Hamad    schedule 23.12.2013
comment
Большое спасибо Хамад. Это частично работает, но посмотрите комментарии, которые я добавил к сообщению Anup Cowkur, в которых подробно описана проблема. - person Roger W; 23.12.2013
comment
хорошо, тогда удалите этот parent.getSelectedItemPosition(); и используйте только позицию для текущего выбранного элемента, тогда он будет работать. - person Hamad; 23.12.2013

Что ж, спасибо, с помощью Анупа и Хамада, я решил свою проблему, что довольно впечатляюще после публикации моего вопроса менее часа назад. Вот код Java, который теперь работает:

@Override
        public void onItemSelected(AdapterView<?> parent, View view,
                int position, long id) {

            // The variable index identifies the position the spinner is in.
            // TextView name, country and description... locks to the
            // TextViews defined in the activity_main.xml layout files.
            int index = parent.getSelectedItemPosition();
            TextView name = (TextView) findViewById(R.id.name);
            TextView country = (TextView) findViewById(R.id.country);
            TextView description = (TextView) findViewById(R.id.description);

            // Used to set Layout Params for the ImageView
            RelativeLayout.LayoutParams lp = (RelativeLayout.LayoutParams) image
                    .getLayoutParams();
            // Clears the rules for when index changes
            lp.addRule(RelativeLayout.CENTER_IN_PARENT, 0);
            lp.addRule(RelativeLayout.ALIGN_PARENT_LEFT, 0);

            // Now we'll check to see if we're in the None Selected spinner
            // position. If true we'll dump the name, country and
            // description TextViews otherwise these will be shown.

            if (index == 0) {

                name.setVisibility(View.GONE);
                country.setVisibility(View.GONE);
                description.setVisibility(View.GONE);

                image.setImageResource(imgs.getResourceId(
                        spinner1.getSelectedItemPosition(), -1));
                // Try and centre the image when none is selected using
                // Layout Params
                lp.addRule(RelativeLayout.CENTER_IN_PARENT);
                image.setLayoutParams(lp);

            } else {

                image.setImageResource(imgs.getResourceId(
                        spinner1.getSelectedItemPosition(), -1));
                // Try and left align the image when the spinner is NOT in
                // the None Selected position using Layout Params
                lp.addRule(RelativeLayout.ALIGN_PARENT_LEFT);
                image.setLayoutParams(lp);

                name.setVisibility(View.VISIBLE);
                country.setVisibility(View.VISIBLE);
                description.setVisibility(View.VISIBLE);

                name.setText(leaders[index]);
                country.setText(states[index]);
                description.setText(descrip[index]);

            }

        }
person Roger W    schedule 23.12.2013