LayoutInflator为什么返回空对象引用?
问题描述:
我正在从扩展活动的类访问布局,当我在该类中使用LayoutInflator
时,它返回空对象引用,但是当我在主活动中使用相同的方法时,它工作正常,请有人帮助我为什么发生这种情况?LayoutInflator为什么返回空对象引用?
public class MenipulateCard extends Activity{
public LinearLayout myCard(
LayoutInflater myInflator =
(LayoutInflater)getApplicationContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
CardView view = (CardView) myInflator.inflate(R.layout.user_layout,null);
LinearLayout ml = new LinearLayout(this);
ml.addView(view);
return ml;
}
返回null对象引用:
java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.Context android.content.Context.getApplicationContext()' on a null object reference at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2724)
,但是当我用同样的方法在主要活动,我可以得到的LinearLayout。请帮我,哥们
答
使用此方法来代替,但要确保你的背景是不是null
View v = LayoutInflater.from(yourContext).inflate(int resource, ViewGroup root, boolean attachToRoot);
你试过context.getSystemServic(),而不是getApplicationContext()。getSystemService? – Darush
android studio不会弹出任何context.getApplicationContext仅用于弹出getBaseContext和getApplicationContext – Mudassir
我的意思是this.getSystemService() – Darush