我在整个应用程序中使用了一个主题,在主题中,文本颜色简单地声明如下:
android:textColor="@android:color/black"
对于位于 Activity 内部的 TextView,颜色应用得很好。但是,当我在列表项(由适配器膨胀)内创建 TextView 时,文本颜色改为白色。
有谁知道需要在主题中声明什么样式才能影响列表项?
列表项的完整 XML:
<CheckBox
android:id="@+id/lt_checkbox"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="8dp"
android:layout_centerVertical="true"
android:layout_alignParentRight="true"/>
<TextView
android:id="@+id/lt_length"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerVertical="true"
android:layout_toLeftOf="@id/lt_checkbox"
android:textSize="24dp"/>
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_margin="8dp"
android:layout_centerVertical="true"
android:layout_toLeftOf="@id/lt_length"
android:layout_alignParentLeft="true"
android:orientation="vertical">
<TextView
android:id="@+id/lt_title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginBottom="12dp"
android:textSize="18dp"/>
<TextView
android:id="@+id/lt_subtitle"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="14dp"/>
</LinearLayout>
列表的 XML:
<ListView
android:id="@+id/altl_list"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
和适配器:
@Override
public View getView(int position, View convertView, ViewGroup parent) {
LocalTrack track = getItem(position);
ItemHolder holder;
if(convertView == null || convertView.getTag() == null) {
convertView = mInflater.inflate(R.layout.listem_track, parent, false);
holder = new ItemHolder();
holder.title = (TextView) convertView.findViewById(R.id.lt_title);
holder.length = (TextView) convertView.findViewById(R.id.lt_length);
holder.checkbox = (CheckBox) convertView.findViewById(R.id.lt_checkbox);
convertView.setTag(holder);
}
else
holder = (ItemHolder) convertView.getTag();
holder.title.setText(track.getTitle());
holder.length.setText(Helpbot.convertMillisToTrackLength(track.getLength()));
holder.checkbox.setChecked(mSelectedTracks.contains(track));
return convertView;
}
最佳答案
发生这种情况是因为您正在使用 Application
的 Context
扩充 ListView
的行布局(LayoutInflater.from( getApplicationContext());
或其他派生),而不是使用您的 Activity
的 Context
。
您将从 getApplicationContext()
和 Activity.this
获得的 Context 之间的区别在于它们中任何一个的 Context
的实现.
Context
,Application
的 Context
和 Activity
都被包裹在一个 ContextWrapper
并将它们的调用代理到内部“Base”Context
。
这里的区别在于 Application
类是一个单例,并且只有一个全局实现用于您的整个应用程序,而每个 Activity - 因为也继承自 ContextWrapper
-每个 Activity
都有自己独特的实现。
这就是为什么 getApplication()
不——也不能——遵守你在 list 中定义的主题的规则,而是遵守你提供的 Context
Activity
做/可以。
我强烈建议您阅读 Dave Smith 的 article关于上下文
。
关于Android 主题不影响列表项内的 TextViews,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27792968/