12

我正在使用ActionBarSherlock,并且正在尝试为行背景自定义activateBackgroundIndicator属性。

如果我使用最新的 android sdk,没有ActionBarSherlock,我可以自定义背景,在res/values/style.xml上创建以下样式,并在AndroidManifest.xml上将其定义为android:theme="@style/Theme.自定义”

<?xml version="1.0" encoding="utf-8"?>
<resources>
  <style name="Theme.Custom" parent="android:Theme.Holo.Light.DarkActionBar">
     <item name="android:activatedBackgroundIndicator">@drawable/activated_background</item>
  </style>
</resources>

然后,我的res/drawable/activated_background.xml包含以下代码:

<selector xmlns:android="http://schemas.android.com/apk/res/android">  
   <item android:state_activated="true" android:drawable="@color/row_activated" />
   <item android:drawable="@android:color/transparent" />  
</selector>

最后,用于定义 ListView 中每一行的代码是:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
              android:orientation="vertical"
              android:layout_width="fill_parent"
              android:layout_height="wrap_content"
              android:background="?android:attr/activatedBackgroundIndicator">
    <TextView
            android:id="@+id/test_row"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:text="@string/sample_string"
            android:textAppearance="?android:attr/textAppearanceMedium"
            android:padding="15dp"/>
</LinearLayout>

结果显示在屏幕截图上。是一个简单的应用程序,在单击列表项时只有一个 ListView 和ListView.CHOICE_MODE_SINGLEgetListView().setItemChecked(position, true) 。

标准选定行的蓝色现在是黄色并且可以完美运行。

没有 ABS 的清单

当我想使用 ActionBarSherlock 应用相同的自定义时,就会出现问题。现在样式文件是下一个,背景显示为蓝色而不是自定义黄色。

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <style name="Theme.Custom" parent="Theme.Sherlock.Light.DarkActionBar">
        <item name="activatedBackgroundIndicator">@drawable/activated_background</item>
        <item name="android:activatedBackgroundIndicator">@drawable/activated_background</item>
    </style>

    <style name="activatedBackgroundIndicator">
        <item name="android:background">?android:attr/activatedBackgroundIndicator</item>
    </style>
</resources>

带有 ABS 的列表

我不知道ActionBarSherlock是否支持android:activatedBackgroundIndicator功能,或者我是否忘记实现需要能够更改默认颜色的东西。

有任何想法吗?

4

1 回答 1

10

最后我找到了解决问题的方法。
这是行适配器中使用的上下文。使用的构造函数如以下代码所示:

public RowAdapter(Activity activity, ArrayList<String> list) {
    this.mContext = activity.getApplicationContext();
    this.elements = list;
    this.theActivity = activity;

    this.inflater = (LayoutInflater) this.mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}

只需将上下文从:
this.mContext = activity.getApplicationContext()(Application-Context)
更改为
this.mContext = activity.getBaseContext()(Activity-Context)即可
解决问题,现在背景是自定义背景。

每当您需要操作视图时,请使用Activity-Context,否则Application-Context就足够了。

这个答案帮助我理解为什么在我的情况下使用getBaseContext()而不是getApplicationContext()

自定义行背景

于 2013-03-12T15:04:40.467 回答