如何在Xamarin.Android中创建视图及制作指定样式视图
Hey there! Let's tackle your two Xamarin.Android questions one by one—first covering the basics of creating views, then diving into building a custom-styled view (I'll use a common modern card-style example since the image isn't here, but you can adapt this to match your specific design!).
There are two primary ways to create views in Xamarin.Android: using XML layouts (the most common approach) or dynamically generating them in code.
1.1 使用XML布局创建视图
XML layouts let you define your UI structure visually and declaratively, which is great for static or semi-static UIs. Here's a simple example:
- Open your project's
Resources/layoutfolder and create a new XML file (e.g.,activity_main.xml). - Add this code to define a vertical layout with a text view and a button:
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" android:padding="16dp"> <TextView android:id="@+id/myTextView" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Hello Xamarin.Android!" android:textSize="20sp" /> <Button android:id="@+id/myButton" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Click Me!" android:layout_marginTop="16dp" /> </LinearLayout>
- In your Activity's
OnCreatemethod, set this layout as the content view and reference the views:
protected override void OnCreate(Bundle savedInstanceState) { base.OnCreate(savedInstanceState); SetContentView(Resource.Layout.activity_main); // Reference the views TextView myTextView = FindViewById<TextView>(Resource.Id.myTextView); Button myButton = FindViewById<Button>(Resource.Id.myButton); // Add a click listener to the button myButton.Click += (sender, e) => { myTextView.Text = "Button clicked!"; }; }
1.2 通过代码动态创建视图
If you need to generate views on the fly (e.g., based on data), you can create them directly in C#. Here's how to replicate the above layout programmatically:
protected override void OnCreate(Bundle savedInstanceState) { base.OnCreate(savedInstanceState); // Create a vertical LinearLayout LinearLayout linearLayout = new LinearLayout(this) { LayoutParameters = new ViewGroup.LayoutParams( ViewGroup.LayoutParams.MatchParent, ViewGroup.LayoutParams.MatchParent ), Orientation = Orientation.Vertical, Padding = new Android.Content.Res.TypedValue().ApplyDimension( Android.Util.ComplexUnitType.Dip, 16, Resources.DisplayMetrics ) }; // Create a TextView TextView myTextView = new TextView(this) { Text = "Hello Xamarin.Android!", TextSize = 20, LayoutParameters = new ViewGroup.LayoutParams( ViewGroup.LayoutParams.WrapContent, ViewGroup.LayoutParams.WrapContent ) }; // Create a Button Button myButton = new Button(this) { Text = "Click Me!", LayoutParameters = new ViewGroup.MarginLayoutParams( ViewGroup.LayoutParams.WrapContent, ViewGroup.LayoutParams.WrapContent ) { TopMargin = (int)Android.Content.Res.TypedValue.ApplyDimension( Android.Util.ComplexUnitType.Dip, 16, Resources.DisplayMetrics ) } }; // Add click listener myButton.Click += (sender, e) => { myTextView.Text = "Button clicked!"; }; // Add views to the layout linearLayout.AddView(myTextView); linearLayout.AddView(myButton); // Set the layout as content view SetContentView(linearLayout); }
Assuming you want a modern card-style view (rounded corners, soft shadow, padding—super common in mobile UIs), here are two approaches:
2.1 使用Drawable资源实现样式
This is the easiest way to add custom backgrounds to existing views.
- Create a new drawable file in
Resources/drawable(e.g.,card_background.xml):
<?xml version="1.0" encoding="utf-8"?> <layer-list xmlns:android="http://schemas.android.com/apk/res/android"> <!-- Shadow layer --> <item> <shape android:shape="rectangle"> <solid android:color="#1A000000" /> <!-- Semi-transparent black for shadow --> <corners android:radius="8dp" /> <padding android:bottom="2dp" android:left="2dp" android:right="2dp" android:top="2dp" /> </shape> </item> <!-- Main card layer --> <item> <shape android:shape="rectangle"> <solid android:color="#FFFFFF" /> <!-- White background --> <corners android:radius="8dp" /> <padding android:bottom="16dp" android:left="16dp" android:right="16dp" android:top="16dp" /> </shape> </item> </layer-list>
- Apply this drawable to a view in your XML layout (e.g., a FrameLayout or LinearLayout):
<FrameLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_margin="16dp" android:background="@drawable/card_background"> <!-- Add your content inside the card here --> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="This is a styled card view!" android:textSize="18sp" /> </FrameLayout>
2.2 自定义View实现复杂样式
If you need more control (e.g., dynamic shadow color, custom animations), create a custom View:
using Android.Content; using Android.Graphics; using Android.Util; using Android.Views; namespace YourAppNamespace { public class CustomCardView : View { private Paint _shadowPaint; private Paint _cardPaint; private RectF _cardRect; private float _cornerRadius = 8f; private float _shadowRadius = 2f; public CustomCardView(Context context) : base(context) { Initialize(); } public CustomCardView(Context context, IAttributeSet attrs) : base(context, attrs) { Initialize(); } public CustomCardView(Context context, IAttributeSet attrs, int defStyleAttr) : base(context, attrs, defStyleAttr) { Initialize(); } private void Initialize() { // Set up shadow paint _shadowPaint = new Paint(PaintFlags.AntiAlias) { Color = Color.ParseColor("#1A000000"), Style = Paint.Style.Fill }; // Set up card paint _cardPaint = new Paint(PaintFlags.AntiAlias) { Color = Color.White, Style = Paint.Style.Fill }; // Enable hardware acceleration for better performance SetLayerType(LayerType.Hardware, null); } protected override void OnSizeChanged(int w, int h, int oldw, int oldh) { base.OnSizeChanged(w, h, oldw, oldh); // Define the card rectangle (offset for shadow) _cardRect = new RectF( _shadowRadius, _shadowRadius, w - _shadowRadius, h - _shadowRadius ); } protected override void OnDraw(Canvas canvas) { base.OnDraw(canvas); // Draw shadow first canvas.DrawRoundRect(_cardRect, _cornerRadius, _cornerRadius, _shadowPaint); // Draw card on top canvas.DrawRoundRect( _shadowRadius, _shadowRadius, Width - _shadowRadius, Height - _shadowRadius, _cornerRadius, _cornerRadius, _cardPaint ); // You can add more drawing logic here (e.g., borders, gradients) } } }
Then use it in your XML layout (make sure to use your full namespace):
<your.app.namespace.CustomCardView android:layout_width="match_parent" android:layout_height="100dp" android:layout_margin="16dp"> <!-- Add your content here --> </your.app.namespace.CustomCardView>
内容的提问来源于stack exchange,提问作者Divinegdk

