Android:getLayoutInflater在静态类中不起作用

时间:2015-06-27 09:37:37

标签: android class

我想在getLayoutInflater static

中使用class

但运行此代码后无法正常工作:

  

MainActivity.java

public class MainActivity extends Activity {

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        LinearLayout post = (LinearLayout) findViewById(R.id.post);
        Commands.readD(post);
    }
}

Commands.java

public class Commands {

    public static void readD(LinearLayout viewPost) {
        LayoutInflater inflater = getLayoutInflater();
        final View viewIn = inflater.inflate(R.layout.viewIn, null);
        final TextView txtNd = (TextView) viewIn.findViewById(R.id.txtNd);
        viewMain.addView(viewIn);
    }
}

此行错误为:

  

对于类型命令

,方法getLayoutInflater()未定义

3 个答案:

答案 0 :(得分:2)

实际上你的静态类需要context

public static void readD(LinearLayout viewPost,Activity context) {

LayoutInflater inflater = context.getLayoutInflater()
 ......
}

或者

另一种方式是

public static void readD(LinearLayout viewPost) {
  LayoutInflater inflater = viewPost.getContext().getLayoutInflator();
 //do your stuff
}

as @ρяσѕρєяK提到

答案 1 :(得分:2)

通过方法

传递Activity
public static void readD(LinearLayout viewPost,Activity context) {
      LayoutInflater inflater = context.getLayoutInflater();
     //do your stuff
}

在onCreate()

 Commands.readD(post,this);

public static void readD(LinearLayout viewPost) {
      LayoutInflater inflater = viewPost.getContext().getLayoutInflator();
     //do your stuff
}

如ρяσѕρєяK提及..

希望这会对你有所帮助。

答案 2 :(得分:1)

发生错误是因为没有上下文而无法实现LayoutInflater。我建议你在方法中传递一个Context param,例如:

public class Commands {

public static void readD(LinearLayout viewMain,Context context) {
    LayoutInflater inflater =LayoutInflater.from(context);
    final View viewIn = inflater.inflate(R.layout.viewIn, null);
    final TextView txtNd = (TextView) viewIn.findViewById(R.id.txtNd);
    viewMain.addView(viewIn);
}

}