为了澄清,我有一个列表,根据员工执行的工作数量而变化。我想在Android应用程序中创建一个页面,其中列表中的每个作业都有一个按钮,列表将增加和减少作业数量。我想以一种允许我改变按钮颜色和边距的方式来做,但我还没找到方法。
答案 0 :(得分:0)
我打算假设您将此标记为C#和Android,您正在使用Xamarin。我相信实现目标的最佳方法是动态创建按钮。
从一个空白的Android解决方案开始,我做了以下更改:
在主布局视图中添加了id“contentLayout”。
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/contentLayout"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent" />
创建一个基本的Job类,并按“优先级”设置背景颜色,作为该过程如何工作的示例。
using Android.App;
using Android.Widget;
using Android.OS;
using Android.Views;
using System.Collections.Generic;
using Android.Content;
namespace App1
{
[Activity(Label = "App1", MainLauncher = true, Icon = "@drawable/icon")]
public class MainActivity : Activity
{
private LinearLayout _contentLayout;
protected override void OnCreate(Bundle bundle)
{
base.OnCreate(bundle);
SetContentView(Resource.Layout.Main);
_contentLayout = FindViewById<LinearLayout>(Resource.Id.contentLayout);
List<MyJob> jobs = GetJobs();
_contentLayout.AddView(GetButtons(this, jobs));
}
private List<MyJob> GetJobs()
{
return new List<MyJob>()
{
new MyJob() { Text = "First Job", Priority = MyJob.PriorityEnum.Low },
new MyJob() { Text = "Second Job", Priority = MyJob.PriorityEnum.Medium },
new MyJob() { Text = "Third Job", Priority = MyJob.PriorityEnum.High },
new MyJob() { Text = "Fourth Job", Priority = MyJob.PriorityEnum.Low },
};
}
private ViewGroup GetButtons(Context context, List<MyJob> jobs)
{
if (jobs == null || jobs.Count == 0)
{
return null;
}
LinearLayout buttonLayout = new LinearLayout(context)
{
Orientation = Orientation.Vertical,
LayoutParameters = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MatchParent, ViewGroup.LayoutParams.WrapContent)
};
foreach (MyJob job in jobs)
{
Button button = new Button(context)
{
LayoutParameters = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MatchParent, ViewGroup.LayoutParams.WrapContent),
Text = job.Text,
};
button.SetBackgroundColor(GetButtonColor(job.Priority));
buttonLayout.AddView(button);
}
return buttonLayout;
}
private Android.Graphics.Color GetButtonColor(MyJob.PriorityEnum priority)
{
switch (priority)
{
case MyJob.PriorityEnum.High:
return new Android.Graphics.Color(255, 0, 0);
case MyJob.PriorityEnum.Medium:
return new Android.Graphics.Color(255, 255, 0);
case MyJob.PriorityEnum.Low:
default:
return new Android.Graphics.Color(0, 255, 0);
}
}
}
internal class MyJob
{
public enum PriorityEnum { Low, Medium, High }
public string Text { get; set; }
public PriorityEnum Priority { get; set; }
}
}
Screen grab of final output - 它需要一些工作,但我相信这会让你朝着正确的方向前进。