Android TextView setText накладывает предыдущий текст

Я хотел бы установить Text в TextView моего приложения (lication). Это код, который я использовал:

TextView lonTextView = (TextView) findViewById(R.id.textViewLonWert);
lonTextView.setText(longitude.toString());

На самом деле это работает, но предыдущий текст все еще отображается! Например, цифра 4 накладывается на цифру 8 (вы больше не можете читать текст).

У меня есть активность, запускающая службу. Затем регистрируем LocalBroadcastReceiver в Activity. Служба периодически отправляет объекты местоположения в активность. Из того места, где я получаю, например. долготу и хотел бы обновить текстовое представление (только содержит долготу) с новой долготой.

Буду очень рад, если у кого-то есть идеи по решению этой проблемы.

ОБНОВЛЕНИЕ: Полный код довольно длинный, поэтому вот соответствующие фрагменты:

Отслеживание активности.java

public class TrackingActivity extends Activity {

// GPSTracker class
GPSTracker gps; 

public String filename;

/* Um eigene Position anzuzeigen */
ArrayList<OverlayItem> overlayItemArray;
protected MapView mapView;
protected MapController mapController;
public Boolean isPause;
public Boolean isTracking;
public MyLocationOverlay myLocationOverlay;
PathOverlay myPath;
List<GeoPoint> path;

public BroadcastReceiver screenReceiver;

/* Textviews setzen */
TextView lonTextView;
TextView latTextView;
TextView altTextView;
TextView accTextView;

// Initiating Menu XML file (menu.xml)
/*@Override
public boolean onCreateOptionsMenu(Menu menu)
{

    MenuInflater menuInflater = getMenuInflater();
    menuInflater.inflate(R.menu.menu_tracking, menu);
    MenuItem mi_startTracking = menu.findItem(R.id.start_tracking);
    mi_startTracking.setVisible(true);
    return true;
}*/

/**
 * Event Handling for Individual menu item selected
 * Identify single menu item by it's id
 * */
@Override
public boolean onOptionsItemSelected(MenuItem item)
{
    ...
}    

@Override

public boolean onPrepareOptionsMenu(Menu menu) {
   ...
}

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_tracking);

    isTracking  = false;
    isPause     = false;

    // create GPS-class object
    gps = new GPSTracker(TrackingActivity.this
                        ,null);

    myPath  = new PathOverlay(Color.RED, this);
    path    = new ArrayList<GeoPoint>();

   /* Map anzeigen */
    mapView = new MapView(this, 500);
    mapView.setTileSource(TileSourceFactory.MAPNIK);
    org.osmdroid.views.MapView.LayoutParams mapParams = new                   org.osmdroid.views.MapView.LayoutParams(
            org.osmdroid.views.MapView.LayoutParams.MATCH_PARENT,
            org.osmdroid.views.MapView.LayoutParams.MATCH_PARENT,
            null, 0, 0, 0);
    /*löst Fehler aus: mapView.setClickable(true);*/
    mapView.setBuiltInZoomControls(true);
    mapController = new MapController(mapView);
    mapView.getController().setZoom(15);


    //--- Create Overlay
    overlayItemArray = new ArrayList<OverlayItem>();

    DefaultResourceProxyImpl defaultResourceProxyImpl   = new DefaultResourceProxyImpl(this);
    MyItemizedIconOverlay myItemizedIconOverlay         = new MyItemizedIconOverlay(
                                                        overlayItemArray, null, defaultResourceProxyImpl);
    mapView.getOverlays().add(myItemizedIconOverlay);
    //---

    //Add current position
    myLocationOverlay = new MyLocationOverlay(this, mapView);
    mapView.getOverlays().add(myLocationOverlay);

    /* Lege Pfad auf Karte */
    mapView.getOverlays().add(myPath);
    mapView.invalidate();
    LinearLayout myLayout = (LinearLayout) findViewById(R.id.trackingLinearLayoutMap);

    myLayout.addView(mapView,mapParams);

}

private BroadcastReceiver gpsDataReceiver = new BroadcastReceiver() {

    @Override
    public void onReceive(Context context, Intent intent) {

        //Log.d("TrackingActivity", "in Receiver");
        /* alles was der Service liefert */
        String action       = intent.getAction();
        Double altitude     = intent.getDoubleExtra("altitude", 0);
        Double longitude    = intent.getDoubleExtra("longitude", 0);
        Double latitude     = intent.getDoubleExtra("latitude", 0);
        Bundle b            = intent.getExtras();
        Location location   = (Location)b.get("location");

        Log.d("received","Receiver: "+longitude+" ; "+latitude);


        //Log.d("TrackingActivity", "vor GeoPoint");
        GeoPoint locGeoPoint = new GeoPoint(latitude, longitude);

                /* Erstelle Pfad */
        if(isTracking){
            path.add(locGeoPoint);
            myPath.addPoint(locGeoPoint);
        }
        //Log.d("TrackingActivity", "nach GeoPoint: "+locGeoPoint.toString());
        mapController.setCenter(locGeoPoint);

        setOverlayLoc(location);

        /* Textviews Werte setzen */
        lonTextView = (TextView) findViewById(R.id.textViewLonWert);
        lonTextView.setText(longitude.toString());
        //lonTextView.invalidate();

        latTextView = (TextView) findViewById(R.id.textViewLatWert);
        latTextView.setText(latitude.toString());
        //latTextView.invalidate();

        altTextView = (TextView) findViewById(R.id.textViewAltWert);
        altTextView.setText(altitude.toString());
        //altTextView.invalidate();

        accTextView = (TextView) findViewById(R.id.textViewAccWert);
        accTextView.setText(Float.toString(location.getAccuracy())+" m");
        //accTextView.invalidate();

        /* Karte aktualisieren */
        mapView.invalidate();

    }
};
...
@Override
protected void onResume() {
    super.onResume();
    /* Registriere BroadcastReceiver für GPSDaten */
    LocalBroadcastManager.getInstance(this).registerReceiver(gpsDataReceiver, new IntentFilter("gpsdata"));

        ...

}
...

Вот мой макет .xml:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/trackingLinearLayout"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >

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

    <TextView
        android:id="@+id/textView1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="kein GPS Signal"
        android:textAppearance="?android:attr/textAppearanceSmall"
        android:textSize="10sp" />

    <LinearLayout
    android:id="@+id/trackingStautsInnerWrapper2"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="horizontal" >
        <TextView
        android:id="@+id/textViewLonLabel"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Länge: "
        android:textAppearance="?android:attr/textAppearanceSmall"
        android:textSize="10sp" />
        <TextView
        android:id="@+id/textViewLonWert"
        android:layout_width="80dp"
        android:layout_height="wrap_content"
        android:text=""
        android:textAppearance="?android:attr/textAppearanceSmall"
        android:textSize="10sp" />
        <TextView
        android:id="@+id/textViewLatLabel"
        android:layout_marginLeft="40dp"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Breite: "
        android:textAppearance="?android:attr/textAppearanceSmall"
        android:textSize="10sp" />
        <TextView
        android:id="@+id/textViewLatWert"
        android:layout_width="80dp"
        android:layout_height="wrap_content"
        android:text=""
        android:textAppearance="?android:attr/textAppearanceSmall"
        android:textSize="10sp" />

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

        <TextView
        android:id="@+id/textViewAltLabel"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Höhe: "
        android:textAppearance="?android:attr/textAppearanceSmall"
        android:textSize="10sp" />
        <TextView
        android:id="@+id/textViewAltWert"
        android:layout_width="80dp"
        android:layout_height="wrap_content"
        android:text=""
        android:textAppearance="?android:attr/textAppearanceSmall"
        android:textSize="10sp" />
        <TextView
        android:id="@+id/textViewAccLabel"
        android:layout_marginLeft="40dp"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Genauigkeit: "
        android:textAppearance="?android:attr/textAppearanceSmall"
        android:textSize="10sp" />
        <TextView
        android:id="@+id/textViewAccWert"
        android:layout_width="80dp"
        android:layout_height="wrap_content"
        android:text=""
        android:textAppearance="?android:attr/textAppearanceSmall"
        android:textSize="10sp" />
    </LinearLayout>
</LinearLayout>
<!--  
<org.osmdroid.views.MapView
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/mapview"
    android:layout_width="fill_parent"
    android:layout_height="match_parent"
    android:clickable="true"/>
-->

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

</LinearLayout>

Hope it helps!


person zuluk    schedule 11.05.2013    source источник
comment
можете ли вы опубликовать полный код и xml?r   -  person Udi Oshi    schedule 11.05.2013
comment
обновил мой вопрос с кодом.   -  person zuluk    schedule 11.05.2013


Ответы (2)


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

Если это не решит проблему, вам может потребоваться заменить кнопку пользовательским представлением с переопределением onDraw с помощью canvas.drawText(), чтобы поместить текст на место. Затем вы можете быть уверены, что стерли всю предыдущую историю ...

ЕСЛИ вам просто нужен непрозрачный черный фон, создайте (или добавьте) файл colors.xml в каталоге res:

<resources>
    <color name="black">#ff000000</color>
</resources>

и добавить:

    android:background="@color/black"

В xml для TextView.

person Neil Townsend    schedule 11.05.2013
comment
Круто, та же проблема. Большое спасибо! - person zuluk; 11.05.2013
comment
Это очень странно! не слышал об этом! Есть еще один способ проверить этот вопрос. попробуйте удалить все другие текстовые представления внутри линейного макета. возможно, один из них накладывается на другой. - person Udi Oshi; 11.05.2013
comment
@UdiOshi Это всегда стоит проверить, но не в вопросе, на который я указываю ... - person Neil Townsend; 11.05.2013
comment
@UdiOshi: я удалил все TextView, кроме одного, но произошел тот же эффект. - person zuluk; 11.05.2013
comment
Теперь я понял, что фон макета черный, но я никогда не определял цвет фона для этого макета. То же самое с цветом текста - он белый. Черный фон и белый цвет текста по умолчанию? Или возможно, что есть сложности с другими файлами layout.xml, где определены linearlayouts с этими настройками? - person zuluk; 11.05.2013
comment
Если вы определите фон для полного альфа-цвета (например, черного), я ожидаю, что он будет работать нормально (согласно вопросу, на который я ссылался). Если вы хотите, чтобы текст имел прозрачный фон, все усложняется. Чего вы пытаетесь достичь? - person Neil Townsend; 11.05.2013
comment
Я хотел бы установить черный фон (без прозрачности - как код, который я разместил в своем вопросе). - person zuluk; 11.05.2013
comment
Обновленный ответ для достижения этого. - person Neil Townsend; 11.05.2013
comment
Я по-прежнему считаю, что лучший способ сделать это — динамически загрузить виджет, приведя его внешнее содержащее представление к ViewGroup. См. мой ответ здесь textview перезапишет предыдущий текст"> stackoverflow.com/questions/22362360/ - person kandroidj; 13.03.2014
comment
@inner_class7 Хорошее решение, поэтому проголосуйте за него, в следующий раз, когда я столкнусь с проблемой, я сравню разные подходы :-) - person Neil Townsend; 14.03.2014
comment
@NeilTownsend Спасибо, да, я был очень доволен результатами. Этот подход дает вам гораздо больше контроля, и вы можете сделать это с любым виджетом. Важно только отметить, что все дочерние виджеты наследуют параметры макета родительского представления. - person kandroidj; 14.03.2014
comment
пришел сюда, чтобы сказать, что у меня также была эта проблема, в нескольких представлениях внутри макета, у которого атрибут фонового ресурса был удален в фиксации моей командой. Снова заменив фон, проблема была устранена. Кажется, это происходит только на 4.4 и ниже, такой же проблемы не возникало на устройствах с Lollipop. - person leRobot; 08.06.2016

Строка android:text="" в

    <TextView
    android:id="@+id/textViewLonWert"
    android:layout_width="80dp"
    android:layout_height="wrap_content"
    android:text=""
    android:textAppearance="?android:attr/textAppearanceSmall"
    android:textSize="10sp" />

является избыточным, вы можете удалить эту строку.

person Neoh    schedule 11.05.2013
comment
Это не ответ на исходный вопрос. Вместо этого было бы лучше в виде комментария. - person Ben H; 15.03.2016