2013-12-23 5 views
0

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

@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" /> 

ответ

4

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

+0

Welthanks Anup, CENTER_IN_PARENT появляется на работу, когда приложение первый стартует, но после выбора что-то иное, чем положение прядильщика по умолчанию, а затем вернуться в положение по умолчанию это не то изображение начинает централизованно выравниваться, когда приложение запускается, перемещается влево, выровненное, когда что-то было выбрано, и остается влево, когда вы возвращаетесь в позицию None Selected. –

+0

Это потому, что вы добавляете новое правило только при изменении индекса. Вы должны удалить старое правило при добавлении нового. Смотрите: http://stackoverflow.com/a/5110767/1369222 –

+0

Спасибо Anup, еще не решен, но вы дали мне полезное преимущество. Понятно, что. –

1

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

@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]); 
      } 

     } 

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

приветствий,

Хамад

+0

Большое спасибо Хамаду. Он частично работает, но см. Комментарии, которые я добавил к сообщению Анупа Коукура, в котором подробно описывается проблема. –

+0

ok, тогда удалите этот parent.getSelectedItemPosition(); и использовать только позицию для текущего выбранного элемента, тогда он будет работать. – Hamad

0

Ну спасибо с помощью Anup и Хамад Я теперь решенной мой proble м, довольно впечатляюще после публикации моего Q менее часа назад. Вот код 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]); 

      } 

     } 
Смежные вопросы