首页 \ 问答 \ 帆布。(Canvas. Single finger draw. if click on button line color must change)

帆布。(Canvas. Single finger draw. if click on button line color must change)

我有绘制线的2类DrawLine.class和注册了按钮和视图元素的xml文件的Main.class。 我需要点击一个按钮,我可以绘制某种颜色。 例如,按下“blue”按钮时,它变成蓝色等。试图按照DrawLine.class中的规定实现,但日志中的错误指向字符串setContentView(R.layout.activity_main); 一般来说,犯错误的地方并不那么重要,如何通过按下按钮来实现渲染颜色的方法。 activity_main.xml中

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/activity_main"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    >


    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal">
        <Button
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:id="@+id/btnW10"
            android:text="Width10"/>
        <Button
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:id="@+id/btnW40"
            android:text="Width40"/>
        <Button
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:id="@+id/btnW70"
            android:text="Width70"/>

    </LinearLayout>
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="20dp"></LinearLayout>
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal">
        <Button
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:id="@+id/btnBlue"
            android:text="Blue"/>
        <Button
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:id="@+id/btnRed"
            android:text="Red"/>
        <Button
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:id="@+id/btnGreen"
            android:text="Green"/>

    </LinearLayout>

    <com.vladislav.canvaswc.DrawLine
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        />
</LinearLayout>

Main.class

public class MainActivity extends AppCompatActivity
{

    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }
}

DrawLine.class

public class DrawLine extends View implements View.OnClickListener
{

    private Paint paint = new Paint();
    private Path path = new Path();

    float width=5f;
    int color;
   //

   // btnB.OnClickListener(this);

    public DrawLine(Context context)
    {
        super(context);
        init(context);

    }
    public DrawLine(Context context, AttributeSet attrs) {
        super(context, attrs);
        init(context);
    }

    public DrawLine(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        init(context);
    }

    public void init(Context context) {
        paint.setColor(color);
        paint.setStyle(Paint.Style.STROKE);
        paint.setStrokeJoin(Paint.Join.MITER);
        paint.setStrokeWidth(width);
        Button btnB=(Button) findViewById(R.id.btnBlue);
        btnB.setOnClickListener(this);
    }


    @Override
    public void onClick(View view) {
        switch(view.getId())
        {
            case R.id.btnBlue: color=Color.BLUE; break;
        }

    }

    @Override
    protected void onDraw(Canvas canvas)
    {
        super.onDraw(canvas);
        canvas.drawPath(path, paint);
    }


    @Override
    public boolean onTouchEvent(MotionEvent event)
    {
        float x = event.getX();
        float y = event.getY();

        switch (event.getAction()) {
            case MotionEvent.ACTION_DOWN:
                path.moveTo(x, y);
                break;
            case MotionEvent.ACTION_MOVE:
                path.lineTo(x, y);
                invalidate();
                break;
            case MotionEvent.ACTION_UP:

                invalidate();
                break;
        }
        invalidate();
        return true;
    }
}

I have 2classes DrawLine.class where the line is drawn and Main.class where the xml file is called in which the buttons and the view element are registered. I need that at the click of a button I can draw a certain color. For example, the button "blue" when it is pressed the line becomes blue, etc. Tried to implement as it is specified in DrawLine.class but an error in the logs points to the string setContentView (R.layout.activity_main); In general, it is not so important where the mistake is made, how to implement the method of rendering the color by pressing the button. activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/activity_main"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    >


    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal">
        <Button
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:id="@+id/btnW10"
            android:text="Width10"/>
        <Button
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:id="@+id/btnW40"
            android:text="Width40"/>
        <Button
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:id="@+id/btnW70"
            android:text="Width70"/>

    </LinearLayout>
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="20dp"></LinearLayout>
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal">
        <Button
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:id="@+id/btnBlue"
            android:text="Blue"/>
        <Button
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:id="@+id/btnRed"
            android:text="Red"/>
        <Button
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:id="@+id/btnGreen"
            android:text="Green"/>

    </LinearLayout>

    <com.vladislav.canvaswc.DrawLine
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        />
</LinearLayout>

Main.class

public class MainActivity extends AppCompatActivity
{

    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }
}

DrawLine.class

public class DrawLine extends View implements View.OnClickListener
{

    private Paint paint = new Paint();
    private Path path = new Path();

    float width=5f;
    int color;
   //

   // btnB.OnClickListener(this);

    public DrawLine(Context context)
    {
        super(context);
        init(context);

    }
    public DrawLine(Context context, AttributeSet attrs) {
        super(context, attrs);
        init(context);
    }

    public DrawLine(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        init(context);
    }

    public void init(Context context) {
        paint.setColor(color);
        paint.setStyle(Paint.Style.STROKE);
        paint.setStrokeJoin(Paint.Join.MITER);
        paint.setStrokeWidth(width);
        Button btnB=(Button) findViewById(R.id.btnBlue);
        btnB.setOnClickListener(this);
    }


    @Override
    public void onClick(View view) {
        switch(view.getId())
        {
            case R.id.btnBlue: color=Color.BLUE; break;
        }

    }

    @Override
    protected void onDraw(Canvas canvas)
    {
        super.onDraw(canvas);
        canvas.drawPath(path, paint);
    }


    @Override
    public boolean onTouchEvent(MotionEvent event)
    {
        float x = event.getX();
        float y = event.getY();

        switch (event.getAction()) {
            case MotionEvent.ACTION_DOWN:
                path.moveTo(x, y);
                break;
            case MotionEvent.ACTION_MOVE:
                path.lineTo(x, y);
                invalidate();
                break;
            case MotionEvent.ACTION_UP:

                invalidate();
                break;
        }
        invalidate();
        return true;
    }
}

原文:https://stackoverflow.com/questions/43955782
更新时间:2022-03-18 15:03

最满意答案

json响应包含一个对象,该对象内部包含一个代表数据结果的json字符串。

您需要反序列化两次,一次用于响应,另一次用于数据结果。

var response = JsonConvert.DeserializeObject<JObject>(responseStr);
var dataResult = (string)response["GetDataResult"];
var cityData = JsonConvert.DeserializeObject<CityData>(dataResult);

The json response contains an object that within itself contains a json string representing the data result.

You need to deserialize twice, once for the response and one more for the data result.

var response = JsonConvert.DeserializeObject<JObject>(responseStr);
var dataResult = (string)response["GetDataResult"];
var cityData = JsonConvert.DeserializeObject<CityData>(dataResult);

相关问答

更多
  • 您可以实现一个包含您在JSON中的字段的类 class MyData { public string t; public bool a; public object[] data; public string[][] type; } 然后使用DeserializeObject的通用版本: MyData tmp = JsonConvert.DeserializeObject(json); foreach (string typeStr in tmp.type[ ...
  • 尝试这个 var dict = JsonConvert.DeserializeObject>(json); 更新: 刚刚意识到你想在VB.NET中使用它 Dim j1 As String = "{ ""JOE"":""0.90000000"",""JOE"":""3.30000000"",""MONROE"":""1.20000000""}" Dim dict = JsonConvert.DeserializeObject(Of Dictionary( ...
  • 您可以通过这种方式反序列化,创建单独的模型类 public class NewModel { public Response GetStudentsListJSONResult { get; set; }; } public class NewModel2 { public NewModel Result { get; set; }; } 然后 NewModel2 response = Newtonsoft.Json.JsonConvert.DeserializeObject
  • 我想你需要逃脱你的json。 以下代码适用于我。 using System; using System.Web.Script.Serialization; namespace ConsoleApplication1 { class Program { private const string Json = @"{ ""SaveData"": { ""TransactionType"": ""2"", ""Date"": ""8 ...
  • 看看这个网站quicktype.io ,它将为您提供以下完整示例 namespace QuickType { using System; using System.Net; using System.Collections.Generic; using Newtonsoft.Json; public partial class Quote { [JsonProperty("asks")] public List
  • json响应包含一个对象,该对象内部包含一个代表数据结果的json字符串。 您需要反序列化两次,一次用于响应,另一次用于数据结果。 var response = JsonConvert.DeserializeObject(responseStr); var dataResult = (string)response["GetDataResult"]; var cityData = JsonConvert.DeserializeObject(dataResult); T ...
  • 有几种方法可以做到。 一种方法是简单地使用JObject并按名称访问字段,例如: jsonObject["data"]["ROTATION"] 。 您可以使用JObject.Parse “反序列化”,并将JSON文本“解析”为JObject 。 或者,您可以编写自己的JsonConverter并告诉JSON.net在反序列化特定类型时使用该转换器(例如JsonConverterAttribute )。 这需要在ReadJson覆盖中手动解析部分JSON文本,并且实际上取决于您期望的数据。 您还可以使用Pre ...
  • 根据你目前的json结构,这应该有效 var items = serializer.Deserialize>(json); // Url instead of Response 如果这对您不起作用,则必须更改json结构以反映Response类的结构。 除非我错过了什么,否则这是必要的json结构 [{ fileUrl:{ fileUrl: "localhost/ContentManager/get/ovYWB0/81/wallpaper" }}] According your cu ...
  • 因为它是一个数组/列表 public class Item { public int ID { get; set; } public int TYPE { get; set; } public int APP_TAG { get; set; } public string alert { get; set; } public string sound { get; set; } public int badge { get; set; } } var ite ...
  • 看一下文档 ,问题是你的json没有声明它的类。 这意味着您明确需要向反序列化器提供Class对象,因为Java泛型只是编译时,而不是运行时。 引用文档: 我们需要替换在实例化反序列化器时刚刚删除的类型信息。 为此,我们将把我们想要使用的类传递给flexjson.JSONDeserializer.deserialize(String, Class)方法,如下所示: Hero hero = new JSONDeserializer().deserialize( jsonHarvey, Hero.c ...

相关文章

更多

最新问答

更多
  • 您如何使用git diff文件,并将其应用于同一存储库的副本的本地分支?(How do you take a git diff file, and apply it to a local branch that is a copy of the same repository?)
  • 将长浮点值剪切为2个小数点并复制到字符数组(Cut Long Float Value to 2 decimal points and copy to Character Array)
  • OctoberCMS侧边栏不呈现(OctoberCMS Sidebar not rendering)
  • 页面加载后对象是否有资格进行垃圾回收?(Are objects eligible for garbage collection after the page loads?)
  • codeigniter中的语言不能按预期工作(language in codeigniter doesn' t work as expected)
  • 在计算机拍照在哪里进入
  • 使用cin.get()从c ++中的输入流中丢弃不需要的字符(Using cin.get() to discard unwanted characters from the input stream in c++)
  • No for循环将在for循环中运行。(No for loop will run inside for loop. Testing for primes)
  • 单页应用程序:页面重新加载(Single Page Application: page reload)
  • 在循环中选择具有相似模式的列名称(Selecting Column Name With Similar Pattern in a Loop)
  • System.StackOverflow错误(System.StackOverflow error)
  • KnockoutJS未在嵌套模板上应用beforeRemove和afterAdd(KnockoutJS not applying beforeRemove and afterAdd on nested templates)
  • 散列包括方法和/或嵌套属性(Hash include methods and/or nested attributes)
  • android - 如何避免使用Samsung RFS文件系统延迟/冻结?(android - how to avoid lag/freezes with Samsung RFS filesystem?)
  • TensorFlow:基于索引列表创建新张量(TensorFlow: Create a new tensor based on list of indices)
  • 企业安全培训的各项内容
  • 错误:RPC失败;(error: RPC failed; curl transfer closed with outstanding read data remaining)
  • C#类名中允许哪些字符?(What characters are allowed in C# class name?)
  • NumPy:将int64值存储在np.array中并使用dtype float64并将其转换回整数是否安全?(NumPy: Is it safe to store an int64 value in an np.array with dtype float64 and later convert it back to integer?)
  • 注销后如何隐藏导航portlet?(How to hide navigation portlet after logout?)
  • 将多个行和可变行移动到列(moving multiple and variable rows to columns)
  • 提交表单时忽略基础href,而不使用Javascript(ignore base href when submitting form, without using Javascript)
  • 对setOnInfoWindowClickListener的意图(Intent on setOnInfoWindowClickListener)
  • Angular $资源不会改变方法(Angular $resource doesn't change method)
  • 在Angular 5中不是一个函数(is not a function in Angular 5)
  • 如何配置Composite C1以将.m和桌面作为同一站点提供服务(How to configure Composite C1 to serve .m and desktop as the same site)
  • 不适用:悬停在悬停时:在元素之前[复制](Don't apply :hover when hovering on :before element [duplicate])
  • 常见的python rpc和cli接口(Common python rpc and cli interface)
  • Mysql DB单个字段匹配多个其他字段(Mysql DB single field matching to multiple other fields)
  • 产品页面上的Magento Up出售对齐问题(Magento Up sell alignment issue on the products page)