我的基本应用理念是在屏幕上绘图。我有一个 Spinner
对象用于选择“笔”的颜色。我让他们设置了一个开关盒来改变“笔”的颜色。 Spinner
在我的 MainActivity
类中。我在名为 Brush_Color
的类中获得了我的“笔”代码。
这是与 Spinner
相关的 MainActivity
的代码。每个案例都引用我的 arrays.xml 中的一种颜色。注释掉的 Paint paint = ...
是我想做的,但没有成功。
public class MainActivity extends ActionBarActivity implements AdapterView.OnItemSelectedListener{
//Paint paint = new Paint(Brush_Choices.this.paint, Brush_Choices.class);
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Spinner spinner = (Spinner) findViewById(R.id.spinner);
ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this,
R.array.color_selector, android.R.layout.simple_spinner_item);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(adapter);
spinner.setOnItemSelectedListener(this);
}
public void onItemSelected(AdapterView<?> parent, View v, int position, long id){
switch(position) {
case 0:
//paint.setColor(Color.BLACK);
break;
case 1:
//paint.setColor(Color.BLUE);
break;
public void onNothingSelected(AdapterView<?> parent){
}
然后这是我的 Brush_Color
类的代码。我试图从这里访问 Paint
对象并在我的 MainActivity
类中使用它。不过我不知道该怎么做。
Path path = new Path();
SparseArray<PointF> points = new SparseArray<>();
Paint paint = new Paint();
public void onDraw(Canvas canvas){
paint.setStyle(Paint.Style.STROKE);
paint.setStrokeWidth(10);
canvas.drawPath(path,paint);
}
最佳答案
public void onDraw(Canvas canvas){
paint.setStyle(Paint.Style.STROKE);
paint.setStrokeWidth(10);
canvas.drawPath(path,paint);
}
在这段代码中,您已经从绘画类中检索了描边宽度。在实现此类代码或从现有来源复制此类代码之前,您应该完整地理解它。从一个类到另一个类访问变量的不同方法可能会有所不同,但我将扩展您已经使用的方法。
您应该在绘画类中有一个用于描边宽度的变量。这应该是一个私有(private)变量。它是私有(private)的原因是因为您不希望类直接访问该变量。 In Java, difference between default, public, protected, and private
在 paint 类中,您应该有两个函数,它们被称为 Getters 和 Setters。 getter 和 setter 的文档 here
我假设它看起来有点像这样:
A Getter 描边宽度:
public static int getStrokeWidth() {
return strokeWidth;
}
一个 Setter 笔划宽度:
public static void setStrokeWidth(int sWidth) {
this.strokeWidth = sWidth;
}
这两个函数允许从另一个现有类访问绘画类,变量在这些函数中定义以确保正确收集您想要收集的变量。您所要做的就是对这些函数中的任何一个调用 static
回调以获取内部变量的值。
所以使用当前示例,如果您要调用:
Paint.getStrokeWidth();
您将检索该 private int strokeWidth;
的值
反之亦然,但这次不是获取值,而是为程序中的当前点设置值。
Paint.setStrokeWidth(10);
此函数将允许您为 paint
类中的变量定义一个值。
参见 es6 call static methods有关静态方法回调的帮助。
关于Java:在另一个类中使用一个类中的变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30017778/