2017-07-29 57 views
0

所以,如果我有一個LinearLayout並有好幾個孩子Views它裏面,說像情侶的Buttons一個TextViewCheckBox,使用LinearLayoutgetChildAt(x)我會再拿到一個未指定View。注意,我沒有在這裏使用xml,所以它都是以編程方式完成的。無論如何找出什麼類型的視圖是視圖?

public class CustomViewClass extends LinearLayout { 

    private Context context; 

    public CustomViewClass (Context context) { 
     super(context); 
     this.context = context; 
     setOrientation(LinearLayout.VERTICAL); 
     setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT)); 
     setBackgroundColor(Color.DKGRAY); 
     // Code which adds Buttons and such to the LinearLayout 
     getChildAt(1) 
    } 

} 

getChildAt(1),反正是有,我可以找出它是什麼樣的View,無論它是一個ButtonTextView或任何progamatically?

回答

0

執行此操作的一種方法是致電getClass。這會爲您提供一個表示視圖類型的Class對象。

例如:

Class clazz = getChildAt(1).getClass(); 

之後,你有這個類,你可以做各種各樣的事吧。例如取得名稱:

System.out.println(clazz.getName()); 

現在你知道它是什麼樣的視圖。

另一種方法是使用instanceof運算符。這裏有一個例子:

if (getChildAt(1) instanceof TexView) { 
    // getChildAt(1) is a TextView or an instance of a subclass of TextView 
} 
0

使用instanceOf方法。示例示例是

if (view instanceof ImageView) 

或者您可以使用下面的名稱查看視圖的類型。但是如果你想對它做任何計算,實例就是最好的選擇。

view.getClass 

if (view.getClass().getName().equalsIgnoreCase("android.widget.ImageView"))