LayoutInflator返回null对象引用的相同语法为什么?

时间:2017-10-19 01:57:40

标签: android

我正在从一个扩展活动的类中访问一个布局,当我在该类中使用LayoutInflator它返回null对象引用时,但是当我在我的主活动中使用相同的方法时它工作正常请有人帮助我为什么这发生在我身上?

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;
    }  

它返回空对象引用:

 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。请帮帮我,好友

1 个答案:

答案 0 :(得分:0)

请改用此方法,但请确保您的上下文不是null

View v = LayoutInflater.from(yourContext).inflate(int resource, ViewGroup root, boolean attachToRoot);