'Android Java Custom view can not keep value passed from activity
I am tring to pass value from Main Activity to Custom View, I created a setColor metod in the CustomView. Inside the setColor metod it output the right value, but the outside the value is not changed, method doesn't effect the variable. Please help me with this problem.
MainActivity create CustomView canvas and send data by canvas.setColor(Color.BLACK)
public class MainActivity extends AppCompatActivity {
com.example.myapplication.MyCanvas myCanvas;
View test;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//test = findViewById(R.id.canvas);
MyCanvas canvas = new MyCanvas(this, null);
canvas.setColor(Color.BLACK);
}
}
CustomView canvas
public class MyCanvas extends View {
public int test;
public MyCanvas(Context context, AttributeSet attrs) {
super(context, attrs);
}
public void setColor(int color) {
this.test = color;
Log.e("test", "setColor " + test);
}
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
Log.e("test", "Color " + test);
}
}
Output of Log.e
2022-02-28 20:06:40.714 29704-29704/com.example.myapplication E/test: setColor -16777216
2022-02-28 20:06:42.314 29704-29704/com.example.myapplication E/test: Color 0
xml file
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
xmlns:custom="http://schemas.android.com/apk/res-auto"
tools:ignore="MissingClass">
<com.example.myapplication.MyCanvas
android:id="@+id/canvas"
android:layout_width="wrap_content"
android:layout_height="500dp" />
<Button
android:id="@+id/button"
android:layout_width="wrap_content"
android:layout_alignParentEnd="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="501dp"
android:layout_marginEnd="158dp"
android:text="Button"
android:layout_height="50dp"/>
</RelativeLayout>
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
