Android custom Preference title size comes out inc

2019-04-02 11:04发布

问题:

This problem turned out to be much more tricky than it first appeared as it wasn't a problem on all but a few devices.

When creating a custom Preference by making it a subclass of Preference and also use a custom layout defined in an XML file in res/layout and use that layout in onCreateView() in the custom Preference it seems you completely loose the layout information the Preference-s normally have. Nothing strange with that, but if you still want a title (together with the new stuff), how do you specify the size of that title if you want it to be the same size as for other preferences? I was sure I had found the correct answer, setting textAppearance to textAppearanceLarge (either in the layout XML-file which seems like the better way or in the Java code in the Preference class) and this works fine on most devices.

This is from the custom Preference layout file:

<TextView
  android:id="@+android:id/title"
  android:layout_alignParentLeft="true"
  android:layout_alignParentTop="true"
  android:layout_width="fill_parent"
  android:layout_height="wrap_content"
  android:textAppearance="?android:attr/textAppearanceLarge"
>
</TextView>

And this is from CustomPreference.onCreateView():

LayoutInflater mInflater = (LayoutInflater) getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
RelativeLayout layout = (RelativeLayout)mInflater.inflate(R.layout.custompreference, parent, false);
// Setting up new stuff
return layout; 

This works and I can change the size of the title to Small or Medium and I need no Java code for the title in the custom Preference class. textAppearanceLarge is 22dp which seems to be the size of the Preference titles on most devices.

But on some, for instance the HTC Sensation an Desire S the Preference title is smaller. The title of the custom Preference comes out too large on these devices. So, the layouts for non custom Preferences clearly don't use textAppearanceLarge but something else.

My question now is: What do they use? Where can I get it for use in my custom Preferece? I have searched the Internet like crazy but I simply fail to find the answer. All examples I can find use textAppearanceLarge (or simply 22dp), probably because nobody has ever noticed that it doesn't always work correctly.

回答1:

Use android:textAppearance="?android:attr/textAppearanceListItem"