2016-01-19 52 views
0

我有一個包含幾個TextView的佈局文件。我想根據點擊動態改變所有人的顏色動態更改佈局文件中所有TextView的顏色

以下是我正在做的只是一個TextView的:

public void openTargets() { 
    TextView targets = (TextView)findViewById(R.id.targets); 
    targets.setTextColor(ContextCompat 
         .getColor(getApplicationContext(),R.color.colorPrimary)); 
} 

手工做同樣的事情對所有TextViews將是非常乏味的。是否可以減少代碼並一次完成?

這是我的佈局文件的樣子:

<LinearLayout 
    android:layout_width="match_parent" 
    android:layout_height="70dp" 
    android:layout_alignParentBottom="true" 
    xmlns:android="http://schemas.android.com/apk/res/android"> 

    <TextView 
     style="@style/BottomNavigation" 
     android:id="@+id/targets" 
     android:text="Targets" 
     android:onClick="openTargets"/> 

...10 more similar TextViews following in the same LinearLayout... 

回答

6

動態更改所有TextViews的顏色佈局文件

使用getChildCountgetChildAt改變所有的TextView的顏色:

public void deepChangeTextColor(ViewGroup parentLayout){ 
    for (int count=0; count < parentLayout.getChildCount(); count++){ 
      View view = parentLayout.getChildAt(count); 
      if(view instanceof TextView){ 
       ((TextView)view).setTextColor(...); 
      } else if(view instanceof ViewGroup){ 
       deepChangeTextColor((ViewGroup)view); 
      } 
    } 
} 
+0

完美:)謝謝 – wadali

2

設置一些標識於母公司的線性佈局parentLL

然後

for(int i=0; i<parentLL.getChildCount();i++) 
{ 
    Random rnd = new Random(); 
    int color = Color.argb(255, rnd.nextInt(256), rnd.nextInt(256), rnd.nextInt(256)); 


    TextView tv = (TextView)parentLL.getChildAt(i); 
    tv.setTextColor(color); 
} 
相關問題