我想在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()未定义
答案 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);
}
}