2015-05-03 44 views
1

我的基本應用程序想法是在屏幕上繪製。我有一個Spinner對象用於選擇「筆」的顏色。我讓他們設置了一個開關盒來改變「筆」的顏色。 Spinner在我的MainActivity類中。我在一個名爲Brush_Color的課程中有我的「筆」代碼。Java:使用另一個類中的變量

下面是我對MainActivity的代碼,它與Spinner有關。每種情況都指向我的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); 
} 

回答

1
public void onDraw(Canvas canvas){ 
    paint.setStyle(Paint.Style.STROKE); 
    paint.setStrokeWidth(10); 
    canvas.drawPath(path,paint); 
} 

在這一領域你已經檢索油漆類筆畫寬度的代碼。在實施此類代碼或從現有源代碼複製此類代碼之前,您應完整了解其內容。從一個類到另一個類訪問變量的不同方法可能會有所不同,但我會擴展您已經使用的一個。

你應該在paint class中爲筆畫寬度設置一個變量。這應該是一個私有變量。它是私有的原因是因爲你不希望類直接訪問該變量。 In Java, difference between default, public, protected, and private

在paint類中你應該有兩個函數存在,它們被稱爲Getters和Setters。對於getter和setter here

我假設它的文檔看起來有點像這樣:

一個getter中風寬度:

public static int getStrokeWidth() { 
    return strokeWidth; 
} 

二傳手中風寬度:

public static void setStrokeWidth(int sWidth) { 
    this.strokeWidth = sWidth; 
} 

這兩個fu nctions允許從另一個現有類訪問paint類,在這些函數中定義變量以確保您希望收集的變量得到正確收集。你所要做的就是調用一個static的回調函數來獲取變量的值。

因此,使用當前的例子,如果你要撥打:

Paint.getStrokeWidth(); 

你會找回那private int strokeWidth;

值與同爲倒過來,但這次不但得不到的值,您將在程序中設置當前點的值。

Paint.setStrokeWidth(10); 

該函數將允許您定義paint類中的變量的值。

請參閱es6 call static methods獲取有關靜態方法回調的幫助。

相關問題