你好我试图添加一个按钮,但我一直收到这个错误:
java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.LinearLayout.addView(android.view.View, android.view.ViewGroup$LayoutParams)' on a null object reference
这是我的代码,它在常规活动中运行良好,它不作为片段工作:
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fav, container, false);
lSecond = (LinearLayout) v.findViewById(R.id.lSecond);
lThird = (LinearLayout) v.findViewById(R.id.lThird);
return v;
}
public void bCreate(String i)
{
LinearLayout.LayoutParams btnParams = new LinearLayout.LayoutParams(matchParent, wrapContent);
Button btnNew = new Button(this.getActivity());
btnNew.setBackgroundResource(R.drawable.button);
btnNew.setTextColor(Color.parseColor("#ffffff"));
btnNew.setText(i);
scale = getResources().getDisplayMetrics().density;
int top = (int) (5 * scale + 0.5f);
int bot = (int) (5 * scale + 0.5f);
if (Second < Third)
{
int left = (int) (10 * scale + 0.5f);
int right = (int) (5 * scale + 0.5f);
btnParams.leftMargin = left;
btnParams.rightMargin = right;
btnParams.topMargin = top;
btnParams.bottomMargin = bot;
lSecond.addView(btnNew, btnParams);
Second++;
btnNew.setOnClickListener(listen);
}
bCreate在onCreate中被调用,而String i - 是来自数据库的字符串
答案 0 :(得分:0)
bCreate()
过早被召唤。您尝试在具有值之前访问lSecond
。在返回之前在bCreate()
中致电onCreateView()
。