findViewById在静态方法中

时间:2013-05-02 15:31:31

标签: android static-methods 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传递给了这个方法,但无法一起完成。

3 个答案:

答案 0 :(得分:7)

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

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

答案 1 :(得分: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();

}

答案 2 :(得分:1)

如果你想坚持使用静态方法,请使用Activity而不是Context作为参数,并像这样执行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作为参数而不是Context或Activity传递:

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