2015-05-22 3 views
0

Я использую разные макеты и показываю в панель действий. Я хочу изменить значение TextView программно, которое я использовал в макете.Невозможно получить доступ к TextView пользовательского ActionBar

Вот мой XML-файл:

<?xml version="1.0" encoding="utf-8"?> 
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" 
       android:layout_width="fill_parent" 
       android:layout_height="fill_parent" 
       android:background="@drawable/splashscreen_background"> 


       <TextView 
        android:id="@android:id/text1" 
        android:layout_width="?attr/actionBarSize" 
        android:layout_height="match_parent" 
        android:textColor="#ff0000" 
        android:textSize="10sp" 
        android:textStyle="bold" 
        android:background="#034552" 
        android:text="M:101" 
        android:textAppearance="?android:attr/textAppearanceLarge" 
        android:gravity="center" 
        android:minHeight="?android:attr/listPreferredItemHeight" 
        android:layout_alignParentLeft="true" 
        android:layout_alignParentTop="true" 
        android:layout_marginLeft="5dp" 
        android:layout_marginTop="5dp" 
        android:layout_marginBottom="5dp"/> 


        <TextView 
        android:id="@android:id/text2" 
        android:layout_width="?attr/actionBarSize" 
        android:layout_height="match_parent" 
        android:textColor="#ff0000" 
        android:textSize="10sp" 
        android:textStyle="bold" 
        android:background="#034552" 
        android:text="N:101" 
        android:textAppearance="?android:attr/textAppearanceLarge" 
        android:gravity="center" 
        android:minHeight="?android:attr/listPreferredItemHeight" 
        android:layout_alignParentRight="true" 
        android:layout_alignParentTop="true" 
        android:layout_marginRight="5dp" 
        android:layout_marginTop="5dp" 
        android:layout_marginBottom="5dp"/> 
</RelativeLayout> 

А вот ява код файла:

 ActionBar ab = getSupportActionBar(); 
     ab.setDisplayShowHomeEnabled(false); 
     ab.setDisplayShowTitleEnabled(false); 
     LayoutInflater li = LayoutInflater.from(this); 
     View customView = li.inflate(R.layout.test, null); 
     TextView tv = (TextView)customView.findViewById(R.id.text1); 
     ab.setCustomView(customView); 
     ab.setDisplayShowCustomEnabled(true); 

Может ли один предложить мне, как я могу изменить значение TextView программно.

ответ

1

В xml заменить android:id="@android:id/text1" на android:id="@+id/text1". То же самое относятся и к TextView с идентификатором text2 ..

и в Java, вы будете иметь возможность программно установить его так:

TextView tv = (TextView)customView.findViewById(R.id.text1); 
tv.setText("Your Text"); 

Чтобы Findout какой разницу между @android: Ид и @ + id, см. это: https://stackoverflow.com/a/9530028/2534007