我创建了一个在特定时间重复的动态视图。视图有2个textViews和2个带默认值的单选按钮。我想从程序中更改Text值但是获取nullpointer异常,这是我的代码:
LayoutInflater inflater = (LayoutInflater)context.getSystemService
(Context.LAYOUT_INFLATER_SERVICE);
LinearLayout scrollViewLinearlayout = (LinearLayout)findViewById(R.id.parent); // The layout inside scroll view
//int count=50;
for(int i = 0; i < Studentlist.length; i++){
String data = Studentlist[i];
String RollNum = data.split("--")[0];
String Name = data.split("--")[1];
LinearLayout layout2 = new LinearLayout(context);
layout2.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT));
View item = inflater.inflate(R.layout.item_layout, null, false);
layout2.addView(item);
layout2.setId(i);
TextView trollnum = (TextView)findViewById(R.id.RollNum);
trollnum.setText(RollNum);
TextView tname = (TextView)findViewById(R.id.Name);
tname.setText(Name);
scrollViewLinearlayout.addView(layout2);
Log.d("Id is: ", trollnum.getText().toString());
我在'trollnum.setText(RollNum);'
获得nullpointer如何更改视图中的文字?
答案 0 :(得分:2)
您正试图在活动的布局中找到不存在的视图,而不是在刚刚充气的布局中找到它。
替换
TextView trollnum = (TextView)findViewById(R.id.RollNum);
TextView tname = (TextView)findViewById(R.id.Name);
使用
TextView trollnum = (TextView) item.findViewById(R.id.RollNum);
TextView tname = (TextView) item.findViewById(R.id.Name);