2015-01-14 1 views
4

Моя деятельность fullscreen.xml имеет этот отрывок, который работает именно так, как я хочу, производя вывод с десятичными знаками выровненную:Как выровнять эти цифры по десятичной форме в Android?

<LinearLayout 
     android:orientation="vertical" 
     android:layout_width="fill_parent" 
     android:layout_height="fill_parent" 
     android:layout_gravity="center_horizontal|top" 
     android:gravity="center"> 

     <TextView 
      android:layout_width="140dp" 
      android:layout_height="24dp" 
      android:text="-0.123" 
      android:id="@+id/acc_x" 
      android:layout_gravity="center_horizontal|top" 
      android:textColor="#ffffff" 
      android:gravity="center_vertical|end" 
      android:layout_margin="0dp" 
      style="@style/Base.TextAppearance.AppCompat.Large" /> 

     <TextView 
      android:layout_width="140dp" 
      android:layout_height="24dp" 
      android:text="0.123" 
      android:id="@+id/acc_y" 
      android:layout_gravity="center_horizontal|top" 
      android:textColor="#ffffff" 
      android:gravity="center_vertical|end" 
      android:layout_margin="0dp" 
      style="@style/Base.TextAppearance.AppCompat.Large" /> 

     <TextView 
      android:layout_width="140dp" 
      android:layout_height="24dp" 
      android:text="99.123" 
      android:id="@+id/acc_z" 
      android:layout_gravity="center_horizontal|top" 
      android:textColor="#ffffff" 
      android:gravity="center_vertical|end" 
      android:layout_margin="0dp" 
      style="@style/Base.TextAppearance.AppCompat.Large" /> 

     <TextView 
      android:layout_width="140dp" 
      android:layout_height="24dp" 
      android:text="99.123" 
      android:id="@+id/acc_T" 
      android:layout_gravity="center_horizontal|top" 
      android:textColor="#ffffff" 
      android:gravity="center_vertical|end" 
      android:layout_margin="0dp" 
      style="@style/Base.TextAppearance.AppCompat.Large" /> 
    </LinearLayout> 

enter image description here

Но когда я рассчитать число и заполнить те же текстовые поля с этим код, изменения выравнивания:

 x = -0.123f; 
     text = (TextView)findViewById(R.id.acc_x); 
     text.setText(String.format("%-8.3f",x)); 

     y = 0.123f; 
     text = (TextView)findViewById(R.id.acc_y); 
     text.setText(String.format("%-8.3f",y)); 

     z = 99.123f; 
     text = (TextView)findViewById(R.id.acc_z); 
     text.setText(String.format("%-8.3f",z)); 

     T = 0; 
     text = (TextView)findViewById(R.id.acc_T); 
     text.setText(String.format("%-8.3f",T)); 

enter image description here

Что я могу сделать, чтобы выравнивание по десятичной точке было запланировано?

Вот мой build.gradle в случае, если имеет значение:

apply plugin: 'com.android.application' 

android { 
compileSdkVersion 21 
buildToolsVersion "21.1.2" 

defaultConfig { 
    applicationId "com.example.app001" 
    minSdkVersion 14 
    targetSdkVersion 21 
    versionCode 1 
    versionName "1.0" 
} 
buildTypes { 
    release { 
    minifyEnabled false 
    proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro' 
    } 
} 
} 

dependencies { 
compile fileTree(dir: 'libs', include: ['*.jar']) 
compile 'com.android.support:appcompat-v7:21.0.3' 
compile 'com.android.support:support-v4:21.0.3' 
} 
+0

Одна вещь, вы не должны указать точные размеры для TextViews, вы можете просто использовать «wrap_content» для их layout_height и layout_width и использование маржи/дополнения для позиционирования. – jmcdonnell40

+0

Используйте таблицу с тремя столбцами, имеющими текстовое представление. Разделите свою строку на две на. и задайте предварительно десятичную часть в первом столбце с гравитационным правом, a. во втором столбце и после десятичной части в третьем столбце с гравитацией слева. Хороший выбор цвета кстати. –

ответ

1

Вам ничего не нужно менять в вашем layout.xml. Я запустил этот фрагмент кода с изменением форматирования строки, и проблема исчезла.

x = -0.123f; 
    text = (TextView)findViewById(R.id.acc_x); 
    text.setText(String.format("%.3f",x)); 

    y = 0.123f; 
    text = (TextView)findViewById(R.id.acc_y); 
    text.setText(String.format("%.3f",y)); 

    z = 99.123f; 
    text = (TextView)findViewById(R.id.acc_z); 
    text.setText(String.format("%.3f",z)); 

    T = 0; 
    text = (TextView)findViewById(R.id.acc_T); 
    text.setText(String.format("%.3f",T)); 
+0

Возможно, это путь для меня. Я попробую это позже, когда у меня появится шанс. – Octopus

+0

Это сделало трюк и выровняло их так, как я хотел, хотя мне непонятно, почему использование указанного формата не работает. – Octopus

0

Проверьте, работает ли это

x = -0.123f; 
text = (TextView)findViewById(R.id.acc_x); 
text.setText(String.format("%-8.3f",x)); 
text.setTextAppearance(context, android.R.Base.TextAppearance.AppCompat.Large); 

y = 0.123f; 
text = (TextView)findViewById(R.id.acc_y); 
text.setText(String.format("%-8.3f",y)); 
text.setTextAppearance(context, android.R.Base.TextAppearance.AppCompat.Large 

z = 99.123f; 
text = (TextView)findViewById(R.id.acc_z); 
text.setText(String.format("%-8.3f",z)); 
text.setTextAppearance(context, android.R.Base.TextAppearance.AppCompat.Large 

T = 0; 
text = (TextView)findViewById(R.id.acc_T); 
text.setText(String.format("%-8.3f",T)); 
text.setTextAppearance(context, android.R.Base.TextAppearance.AppCompat.Large 
+0

Я получаю сбои сборки с «не могу найти контекст символьной переменной» и «не могу найти символьную переменную Base». Я могу добавить «этот» для «контекста», но я не уверен, что делать с «базой». (?) – Octopus

+0

Это стиль, который вы определили в своем xml. Попробуйте "android.R.TextAppearance.AppCompat.Large" – VizZy

+0

Я могу использовать эту строку кода: 'text.setTextAppearance (this, android.R.style.TextAppearance_Large);' но нет diff – Octopus

2

Использование android:gravity="right" на ваших TextView с.

Это будет выровнять правый край.

Затем удаляем -8 пространство отступы, не нужно сейчас:

text.setText(String.format("%.3f",y)); 

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

+0

layout_width должен иметь фиксированный dp. – timmyt123

+0

@ timmyt123 почему и какая ширина макета? – weston

+0

Привет, TextView layout_width. Если layout_width - wrap_content, то гравитация не сможет его переместить. Я заявлял это для других, потому что создатель имеет фиксированную ширину 140 дп. – timmyt123