2017-06-01 140 views
-1

我對android開發非常陌生,但知道一點Java。我有問題知道在我的代碼中放置Toast.setGravity(Gravity.TOP,0,0)的位置。非靜態setGravity不能從靜態上下文中引用

下面的代碼:

package ca.ignitestudio.geoquiz; 

import android.support.v7.app.AppCompatActivity; 
import android.os.Bundle; 
import android.view.Gravity; 
import android.view.View; 
import android.widget.Button; 
import android.widget.Toast; 


public class QuizActivity extends AppCompatActivity { 

private Button mTrueButton; 
private Button mFalseButton; 


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



    mTrueButton = (Button) findViewById(R.id.true_button); 
    mTrueButton.setOnClickListener(new View.OnClickListener(){ 
     @Override 
     public void onClick(View v) { 
      Toast.makeText(QuizActivity.this, R.string.correct_toast, Toast.LENGTH_SHORT).show(); 
      Toast.setGravity(Gravity.TOP,0,0); 
     } 
    }); 
    mFalseButton = (Button) findViewById(R.id.false_button); 
    mFalseButton.setOnClickListener(new View.OnClickListener() { 
     @Override 
     public void onClick(View v) { 
      Toast.makeText(QuizActivity.this, R.string.incorrect_toast, Toast.LENGTH_SHORT).show(); 
     } 
    }); 
} 

}

+0

你可以標記'setGravity'爲'static'例如'公共靜態setGravity(..)'? –

+0

不,我不能,因爲如果我這樣做會給我更多的錯誤。 –

+0

那麼makeText是如何工作的呢? –

回答

3

你將不得不調用setGravity這樣:

Toast toast = Toast.makeText(test.this,"bbb", Toast.LENGTH_LONG); 
    toast.setGravity(Gravity.CENTER, 0, 0); 
    toast.show(); 
+0

擊敗我約40秒。不應該浪費時間格式化我的代碼... :) – Ginandi

+0

謝謝你。這工作。我有正確的想法,但它是錯誤的。 –

3

setGravity是不是一個靜態方法,所以你應該叫setGravity你吐司實例,即

Toast t = Toast.makeText(QuizActivity.this, R.string.correct_toast, Toast.LENGTH_SHORT); 
t.setGravity(Gravity.TOP,0,0); 
t.show(); 
+0

這是一個40秒錯過的投票:) –

2

您需要在實例上調用setGravity(),而不是在類上。更改

Toast.makeText(QuizActivity.this, R.string.correct_toast, Toast.LENGTH_SHORT).show(); 
Toast.setGravity(Gravity.TOP,0,0); 

Toast toast = Toast.makeText(QuizActivity.this, R.string.correct_toast, Toast.LENGTH_SHORT); 
toast.setGravity(Gravity.TOP,0,0); 
toast.show(); 
相關問題