Android 使用自定义样式参照设置视图的样式
我正在尝试使用自定义属性设置一个Android 使用自定义样式参照设置视图的样式,android,xamarin.android,Android,Xamarin.android,我正在尝试使用自定义属性设置一个RelativeLayout appNS:style1="@style/RelativeLayout2" 在使用静态方法构造期间读取此属性的值 GetStyle(context, attributeSet) 并传递给相应的基构造函数 public RelativeLayout2(Context context, IAttributeSet attributeSet) : base(context, attributeSet, 0, GetStyle(
RelativeLayout
appNS:style1="@style/RelativeLayout2"
在使用静态方法构造期间读取此属性的值
GetStyle(context, attributeSet)
并传递给相应的基构造函数
public RelativeLayout2(Context context, IAttributeSet attributeSet)
: base(context, attributeSet, 0, GetStyle(context, attributeSet))
{
}
@style/RelativeLayout2
中的任何样式都不会生效,并且可能与单独的问题相关
尽管如此,有没有更合适的、支持框架的方法来达到这个目的,因为这似乎是一种黑客行为?
attrs.xml
<?xml version="1.0" encoding="utf-8"?>
<resources>
<declare-styleable name="RelativeLayout2">
<attr name="style1" format="reference"></attr>
</declare-styleable>
</resources>
<resources>
<style name="RelativeLayout2">
<item name="android:layout_width">40dp</item>
<item name="android:layout_height">300dp</item>
<item name="android:background">#114499</item>
<item name="android:padding">50dp</item>
</style>
</resources>
<?xml version="1.0" encoding="utf-8"?>
<InflationWithStyle.RelativeLayout2
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:appNS="http://schemas.android.com/apk/res/InflationWithStyle.InflationWithStyle"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
appNS:style1="@style/RelativeLayout2">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Needs more style."/>
</InflationWithStyle.RelativeLayout2>
@style/RelativeLayout2中的任何样式都不会生效
请参考我的答案
您可以尝试使用style=“@style/RelativeLayout2”
,在我这方面效果很好
using Android.App;
using Android.Content;
using Android.OS;
using Android.Support.V7.App;
using Android.Runtime;
using Android.Util;
using Android.Widget;
namespace InflationWithStyle
{
[Activity(Label = "@string/app_name", Theme = "@style/AppTheme", MainLauncher = true)]
public class MainActivity : AppCompatActivity
{
protected override void OnCreate(Bundle savedInstanceState)
{
base.OnCreate(savedInstanceState);
// Set our view from the "main" layout resource
SetContentView(Resource.Layout.activity_main);
}
}
public class RelativeLayout2 : RelativeLayout
{
public RelativeLayout2(Context context, IAttributeSet attributeSet)
: base(context, attributeSet, 0, GetStyle(context, attributeSet))
{
}
private static int GetStyle(Context context, IAttributeSet attributeSet)
{
return ReadStyleAttribute(context, attributeSet);
}
private static int ReadStyleAttribute(Context context, IAttributeSet attributes)
{
Android.Content.Res.TypedArray typedArray = context.ObtainStyledAttributes(attributes, Resource.Styleable.RelativeLayout2);
int styleAttr = typedArray.GetResourceId(Resource.Styleable.RelativeLayout2_style1, 0);
typedArray.Recycle();
return styleAttr;
}
}
}