簡體   English   中英

單擊子布局中的元素時,更改可擴展列表子視圖的背景

[英]Change background of Expandable List child view when an element in child layout is clicked

單擊子級時,我需要在可擴展列表視圖中更改子級視圖的背景。

子行的布局類似於:

<RelativeLayout>     //Selector is placed for this layout
    ....
   <RelativeLayout>
      .... 
       <RelativeLayout>
         ....
         <TextView>
        ....
    ....

選擇:

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">

  <item android:state_pressed="true"
        android:drawable= "@drawable/greyish"/>
</selector>

現在,當我單擊TextView時,我想更改整個行的背景(最上層的相對布局包括在每個具有子布局的視圖上)。 我如何觸發頂級相對布局的選擇器。

另外,當OnChildClick()收到回調時,行的背景也會更改(由於選擇器放置在頂層布局中)。

我的嘗試是:

在TextView的onlclick方法中:

   ((RelativeLayout)(nameView.getParent().getParent().getParent())).setPressed(true);

但這不會導致行布局更改背景顏色。

問題:

最終,您想從其childView觸發parentView的選擇器。

在您的父布局中,添加以下行:

android:addStatesFromChildren="true"

如果您在Java代碼中具有parentView的引用,則可以通過使用以下命令完成任務:

parentView.setAddStatesFromChildren(true);

其中,parentView是您的父級布局,即: RelativeLayout

注意:

確保您的子視圖不會復制父項的狀態。 即: android:duplicateParentStatechildView.setDuplicateParentState(true)

希望對您有所幫助!

您是否可以不只是給想要給元素上色的布局提供ID,然后再輸入類似的內容:

layout_with_child_views = (RelativeLayout)nameView.getRootView().findViewById(id)

如果您的方法返回正確的視圖,那么您當然也可以堅持。

然后獲取所有子元素並更改背景顏色:

for (int i = 0; i < layout_with_child_views.getChildCount(); i++) {
   View child = (View) layout_with_child_views 
                .getChildAt(i);
   tintBackground(child);       
}

private void tintBackground(View view) {
    ColorDrawable[] color = { new ColorDrawable(Color.WHITE),
            new ColorDrawable(Color.GREY) };
    TransitionDrawable trans = new TransitionDrawable(color);
    view.setBackgroundDrawable(trans);
    trans.startTransition(500);

}

編輯:我一直在搜索,對我來說似乎您應該能夠使用ExpandableListView的可用偵聽器,以便在ExpandableListAdapter中:

    @Override
    public void onChildClick(ExpandableListView parent, View v, int groupPosition, int childPosition, long id) {
        // use the parent to set default color to all other entries

        // v is the view within the expandable list/ListView that was clicked
               for (int i = 0; i < v.getChildCount(); i++) {
                   View child = (View) v.getChildAt(i);
                   // do highlighting       
               }
    }

我自己尚未嘗試過此操作,目前無法設置測試項目。 只是想給您一種替代方法,以防您未嘗試過類似的操作。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM