2013-05-02 71 views
6

我有这样的静态方法:findViewById一个静态方法

public static void displayLevelUp(int level, Context context) { 

    LayoutInflater inflater = (LayoutInflater) context 
      .getSystemService(Context.LAYOUT_INFLATER_SERVICE); 

    View layout = inflater.inflate(R.layout.custom_level_coast, 
      (ViewGroup) findViewById(R.id.toast_layout_root)); // this row 

    TextView text = (TextView) layout.findViewById(R.id.toastText); 
    text.setText("This is a custom toast"); 

    Toast toast = new Toast(context); 
    toast.setGravity(Gravity.CENTER_VERTICAL, 0, 0); 
    toast.setDuration(Toast.LENGTH_LONG); 
    toast.setView(layout); 
    toast.show(); 

    Toast.makeText(context, String.valueOf(level), Toast.LENGTH_SHORT) 
      .show(); 

} 

但是,我无法弄清楚如何获得第一findViewById为它说,这是一个非静态方法发挥好本。我明白为什么会这样说,但必须有一种解决方法?我将context传入此方法,但无法一起工作。

+2

您不需要传递上下文对象,而是传递视图对象。一个持有你的意见 – edoardotognoni 2013-05-02 15:33:59

+1

为什么不只是使视图类宽变量,并访问它的方式 – tyczj 2013-05-02 15:34:44

+0

@Wamasa这是正确的答案..信息它 – Pragnani 2013-05-02 15:37:40

回答

6

你可以做的一件事是让视图变成一个类变量并使用它。我实际上不建议这样做,但如果你需要快速和肮脏的东西,它会工作。

将视图作为参数传递将是首选方式

+0

谢谢,不敢相信我没有想到这一点。 – KickingLettuce 2013-05-02 15:46:45

2

这有点不可思议。但是你可以传递根视图作为参数。

//some method... 
ViewGroup root = (ViewGroup) findViewById(R.id.toast_layout_root); 
displayLevelUp(level, context, root); 
//some method end... 


public void displayLevelUp(int level, Context context, ViewGroup root) { 

LayoutInflater inflater = (LayoutInflater) context 
     .getSystemService(Context.LAYOUT_INFLATER_SERVICE); 

View layout = inflater.inflate(R.layout.custom_level_coast, 
     root); 

TextView text = (TextView) layout.findViewById(R.id.toastText); 
text.setText("This is a custom toast"); 

Toast toast = new Toast(context); 
toast.setGravity(Gravity.CENTER_VERTICAL, 0, 0); 
toast.setDuration(Toast.LENGTH_LONG); 
toast.setView(layout); 
toast.show(); 

Toast.makeText(context, String.valueOf(level), Toast.LENGTH_SHORT) 
     .show(); 

} 
1

如果你想坚持一个静态方法利用活动的,而不是作为语境参数做像这样一个activity.findViewById:

public static void displayLevelUp(int level, Activity activity) { 
    LayoutInflater inflater = (LayoutInflater) activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE); 
    View layout = inflater.inflate(R.layout.toastText, (ViewGroup) activity.findViewById(R.id.abs__action_bar_container)); // this row 

另一种方式来做到这一点是通过父母的ViewGroup作为参数而不是上下文或活动:

public static void displayLevelUp(int level, ViewGroup rootLayout) { 
    View layout = rootLayout.inflate(rootLayout.getContext(), R.layout.custom_level_coast, rootLayout.findViewById(R.id.toast_layout_root)); // this row