2016-12-26 38 views
2

我幾乎在所有的類中都有這種方法。靜態成員被實例引用訪問的最佳解決方案

//listener - info 
private void clickInfoListener(final ImageView iv, final int title, final int text){ 
    iv.setOnClickListener(new View.OnClickListener() { 
     @Override 
     public void onClick(View v) { 
      materialHelper.showInfoDialog(MainActivity.this, iv, title, text); 
     } 
    }); 
} 

在輔助類

public static void showInfoDialog(Context context, final ImageView iv, final int title, final int text){ 
    iv.setImageResource(R.drawable.ic_info_touched); 
    // 
    AlertDialog.Builder builder = new AlertDialog.Builder(context); 
    builder.setCancelable(true); 
    builder.setTitle(title); 
    builder.setMessage(text); 
    builder.setPositiveButton(R.string.gotIt, null); 
    builder.show(); 
    // 
    Handler handler = new Handler(); 
    handler.postDelayed(new Runnable() { 
     public void run() { 
      iv.setImageResource(R.drawable.ic_info_primary); 
     } 
    }, 25); 
} 

我得到的「靜態成員被實例引用訪問」 lint警告的訪問這個靜態方法。我不知道如何在這裏不使用「this」。所以我有兩個選擇。

1)忽略lint警告

2)刪除了 「靜態」 在我的helper方法。

哪個更好?或者提出第三種解決方案。

回答

3

或者提出第三種解決方案。

materialHelper替換爲showInfoDialog()所在的類名稱。根據您的描述,materialHelper是此類的一個實例。

+0

真棒!將在5分鐘內接受。 – seekingStillness

8

該警告說您正在通過實例materialHelper調用靜態方法showInfoDialog,而不是通過類MaterialHelper本身。這是「不好的」,因爲它表明該方法實際上是一個實例方法,取決於實例中的某個狀態。

的解決方案是與

MaterialHelper.showInfoDialog(...) 
+1

哎呀,我開始在另一個人發佈之前輸入這個答案......我會留下這個答案,因爲它會給出更多的解釋。 –

2

例如更換

materialHelper.showInfoDialog(...) 

無處不在你的代碼,假設

public static YourClass { 
//.. the other code 
    private void clickInfoListener(final ImageView iv, final int title, final int text){ 
     iv.setOnClickListener(new View.OnClickListener() { 
      @Override 
      public void onClick(View v) { 
       materialHelper.showInfoDialog(MainActivity.this, iv, title, text); 
      } 
     }); 
    } 

    public static void showInfoDialog(Context context, final ImageView iv, final int title, final int text){ 
     iv.setImageResource(R.drawable.ic_info_touched); 
     // 
     AlertDialog.Builder builder = new AlertDialog.Builder(context); 
     builder.setCancelable(true); 
     builder.setTitle(title); 
     builder.setMessage(text); 
     builder.setPositiveButton(R.string.gotIt, null); 
     builder.show(); 
     // 
     Handler handler = new Handler(); 
     handler.postDelayed(new Runnable() { 
      public void run() { 
       iv.setImageResource(R.drawable.ic_info_primary); 
      } 
     }, 25); 
    } 
    } 


//somewhere 
YourClass materialHelper = new YourClass(); 

所以。

此方法showInfoDialog(MainActivity.this, iv, title, text);是「靜態方法」

這意味着:這個方法用於此類(靜態變量太)的所有實例共享。它的名稱在哪裏並不重要。這就是爲什麼林特說: 「哦,天哪,你爲什麼使用這個實例調用這個靜態方法?它可能會改變其他實例中的共享值!小心!」。 Java會理解你的代碼,但這是一個小錯誤(你的誤解)。這就是爲什麼正確的解決辦法是使用這樣的:

YourClass.showInfoDialog(MainActivity.this, iv, title, text);

0

與使用:

import static com.yourcompany.yourproject.materialHelper.showInfoDialog;