9

我有这个静态方法:

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了这种方法,但无法将它们一起解决。

4

3 回答 3

9

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

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

于 2013-05-02T15:43:50.940 回答
2

如果您想坚持使用静态方法,请使用 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
于 2013-05-02T15:41:12.200 回答
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();

}
于 2013-05-02T15:38:03.573 回答