【发布时间】:2013-02-14 11:29:03
【问题描述】:
我有一个带有以下代码的 styles.xml:
<resources>
<style name="general_font" parent="@android:style/TextAppearance">
<item name="android:textSize">12sp</item>
</style>
</resources>
我还有一个包含文本视图的布局(general_layout.xml)
<TextView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:text="@string/text1"
style="@style/general_font"/>
现在,在我的活动中,在内容准备好之前,我想根据屏幕高度将 textSize 更改为 general_font 样式。
这是我的活动课:
public class GeneralActivity extends Activity{
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
scaleTextSize(getHeightOfScreen());
setContentView(R.layout.general_layout);
}
private int getHeightOfScreen(){
DisplayMetrics metrics = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(metrics);
return metrics.heightPixels;
}
public void scaleTextSize(int height){
if(height<=320){
// Change textSize item of general_font style
}
else if(height<=480){
// Change textSize item of general_font style
}
else if(height<=800){
// Change textSize item of general_font style
}
else{
// Change textSize item of general_font style
}
}
}
有可能吗??谢谢大家的建议..
【问题讨论】:
-
我会为不同的屏幕尺寸创建不同的样式,并使用布局文件(/res/layout)中的样式。按此处所述区分布局文件:developer.android.com/guide/practices/screens_support.html
-
感谢您的评论。是的,但是有一些我没有提到的事情。在布局中我有 8 个 textView。我希望所有 textview 样式都来自一种样式。如果我创建不同的样式,我应该将所有文本视图迭代到 setStyle Right ?我不想迭代所有文本视图,我只想更改一项,所有文本视图都采用此功能。
-
如果你不想做太多,那么为你需要的每个屏幕布局使用一个主题。主题适用于您的整个应用程序/活动。定义样式的主题将位于 /res/values 文件夹中。例如 /res/values-h800dp。请参阅此问题以了解与您类似的问题:stackoverflow.com/questions/8148749 /use-different-theme-depending-on-if-device-is-android-tablet-or-phone。我没有在代码中手动执行此操作的经验。这就是为什么我的答案在 cmets 中。
-
我现在清楚了。我为此活动创建了不同的主题,其中包括 textSize 属性。根据高度我为活动设置了一个主题。非常感谢你
-
很高兴能帮上忙。
标签: android textview android-styles