Trả lời

6

API ActionBar không có cách nào để truy xuất nền hiện tại Drawable hoặc màu sắc.

Tuy nhiên, bạn có thể sử dụng Resources.getIdentifier gọi View.findViewById, lấy ActionBarView, sau đó gọi View.getBackground để lấy Drawable. Mặc dù vậy, điều này vẫn sẽ không cung cấp cho bạn màu sắc. Cách duy nhất để làm điều đó là chuyển đổi Drawable thành một Bitmap, sau đó sử dụng một số loại color analyzer để tìm màu chủ đạo.

Dưới đây là ví dụ về việc truy xuất ActionBarDrawable.

final int actionBarId = getResources().getIdentifier("action_bar", "id", "android"); 
    final View actionBar = findViewById(actionBarId); 
    final Drawable actionBarBackground = actionBar.getBackground(); 

Nhưng có vẻ như giải pháp dễ nhất là tạo thuộc tính của riêng bạn và áp dụng nó trong chủ đề của bạn.

Dưới đây là một ví dụ về điều đó:

thuộc tính Tuỳ chỉnh

<attr name="drawerLayoutBackground" format="reference|color" /> 

Khởi tạo thuộc tính

<style name="Your.Theme.Dark" parent="@android:style/Theme.Holo"> 
    <item name="drawerLayoutBackground">@color/your_color_dark</item> 
</style> 

<style name="Your.Theme.Light" parent="@android:style/Theme.Holo.Light"> 
    <item name="drawerLayoutBackground">@color/your_color_light</item> 
</style> 

Sau đó, trong bố trí có chứa DrawerLayout của bạn, áp dụng các thuộc tính android:background như thế này:

android:background="?attr/drawerLayoutBackground" 

Hoặc bạn có thể lấy nó sử dụng một actionBar.getBackground TypedArray

@Override 
protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 

    final TypedArray a = obtainStyledAttributes(new int[] { 
      R.attr.drawerLayoutBackground 
    }); 
    try { 
     final int drawerLayoutBackground = a.getColor(0, 0); 
    } finally { 
     a.recycle(); 
    } 

} 
+4

() trả về cho tôi null. Tôi có làm điều gì sai? – kalehv

+0

@kalehv bạn có thiết lập nền bằng getActivity(). GetActionBar(). SetBackgroundDrawable (...)? Nếu không được thiết lập, bạn thực sự sẽ nhận được một giá trị null. – hcpl

Các vấn đề liên quan