我是编程新手,我在将变量从活动传递到自定义视图时出现问题。
在我的主要活动中,我使用以下命令将字符串放入新活动(分析):
Intent a = new Intent (this, typeof(Analysis));
a.PutExtra("speedvalues", mapclass.Speed());
StartActivity (a);
在Analysis活动中,我使用以下方法检索它:
string s = Intent.GetStringExtra("speedvalues");
一切正常。但是,我需要将此字符串传递给我打开新活动时调用的另一个类(我的自定义视图类)。因为我需要这个字符串来使用我的自定义视图类绘制图形/线。
有人可以告诉我怎么做吗?我尝试将字符串s声明为静态字符串,但这导致了异常错误。
编辑:
以下是我自定义View类的一部分:
class Graph : View
{
List<int> speedvalues = new List<int>(StringToListInt(VARIABLE FROM ACTIVITY));
List<PointF> graphpoints = new List<PointF>();
int padding = 100;
public Graph(Context c) : base(c)
{
this.SetBackgroundColor(Color.White);
}
public float MaxSpeed()
{ [...] }
public static List<int> StringToListInt(string x)
{ [...] }
public void GraphPoints()
{ [...] }
protected override void OnDraw(Canvas cv)
{ [...] }
编辑2:
谢谢你的答案!我检查了最有帮助的一个。
我自己也找到了解决方案。我创建了一个新的静态字符串和一个静态方法。我将新的静态字符串赋值为&#34; speedvalues&#34;使用静态方法:
public class Analysis : Activity
Graph graph;
public static string s5;
protected override void OnCreate (Bundle bundle)
{
[...]
string s4 = Intent.GetStringExtra("speedvalues");
s5 = StringToG (s4);
graph = new Graph(this);
}
private static string StringToG(string s)
{
return s;
}
当然,在Graph类中,我使用:
检索值string speedvalues = Analysis.s5;
到目前为止这个有效。这个版本更好还是更差?
答案 0 :(得分:0)
您正在分配值,并且已经调用了ondraw。 因此,为了防止提取,请找到以下修改过的代码。
class Graph : View
{
List<int> speedvalues;
List<PointF> graphpoints = new List<PointF>();
int padding = 100;
bool isReady = false;
public Graph(Context c) : base(c)
{
this.SetBackgroundColor(Color.White);
}
public float MaxSpeed()
{ [...] }
public static List<int> StringToListInt(string x)
{ [...] }
public void GraphPoints()
{ [...] }
public void ReadyToDraw(bool ready)
{
isReady=ready;
}
public static List<int> StringToListInt(string x)
{
speedvalues=new List<int>(StringToListInt(x));
}
protected override void OnDraw(Canvas cv)
{
base.OnDraw(canvas);
if(ReadyToDraw)
{
//Your drawing code
}
}
}
然后传递如下的值
string s = Intent.GetStringExtra("speedvalues");
Graph g=new Graph(this);
g.StringToListInt(s);//Assign values
g.ReadyToDraw(true);//Set it is ready to draw
g.invalidate(); // Draw
答案 1 :(得分:0)
除了其他答案,您还有另一个名为共享偏好设置的选项。
您可以将变量存储在主要活动中,并在任何课程中获取。
有许多教程通过谷歌找到,例如这个
答案 2 :(得分:-1)
List<int> speedvalues = new List<int>(StringToListInt(VARIABLE FROM ACTIVITY));
List<int> speedvalues ;
public Graph(Context c) : base(c)
{
this.SetBackgroundColor(Color.White);
}
public Graph(Context c , string speedvalues ) : base(c)
{
this.peedvalues = new List<int>(StringToListInt(speedvalues));
this.SetBackgroundColor(Color.White);
}
string s4 = Intent.GetStringExtra("speedvalues");
s5 = StringToG (s4);
graph = new Graph(this);
string s4 = Intent.GetStringExtra("speedvalues");
graph = new Graph(this , StringToG(s4));
class Graph : View
{
List<int> speedvalues ;
public Graph(Context c , string speedvalues ) : base(c)
{
this.peedvalues = new List<int>(StringToListInt(speedvalues));
this.SetBackgroundColor(Color.White);
}
}