每次我动态地将图像视图添加到我的线性布局时,我都会得到一个空指针异常。
LinearLayout tables = (LinearLayout) findViewById(R.id.table);
for(int i = 0; i < data.length; i++){
ImageView image = new ImageView(getApplicationContext());
try{
int imgID = getResources().getIdentifier(data[i], "drawable", "package");
image.setImageResource(imgID);
}catch(Exception e){
int imgID = getResources().getIdentifier("nia", "drawable", "package");
image.setImageResource(imgID);
}
tables.addView(image); //NULL POINTER THROWN HERE
}
当我调试时,imgID有一个值,所以我知道它的工作原理。我只是不明白为什么它为null
答案 0 :(得分:3)
如果这是导致空指针异常的行:
tables.addView(image);
然后tables
为空,只是findViewById()在当前布局中找不到任何ID为R.id.table
的视图。
(如果您需要帮助找出tables
为空的原因,请将您传递的布局发布到setContentView()
)
从评论中添加
以下是创建PopupWindow的一般方法。这使用LayoutInflator来扩展布局,以便我们可以访问它以动态地向布局添加元素。 (请注意,我们的范围是popupLayout.findViewById(...)
}:
public class Example extends Activity {
private PopupWindow popupWindow;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
TextView text = (TextView) findViewById(R.id.text);
text.setOnClickListener(new OnClickListener() {
public void onClick(View view) {
createPopup(view);
}
});
}
public void createPopup(View view) {
LayoutInflater layoutInflater = (LayoutInflater) getSystemService(LAYOUT_INFLATER_SERVICE);
View popupLayout = layoutInflater.inflate(R.layout.popup, null);
// Customize popup's layout here
Button dismissButton = (Button) popupLayout.findViewById(R.id.dismiss);
dismissButton.setOnClickListener(new OnClickListener() {
public void onClick(View view) {
popupWindow.dismiss();
}
});
popupWindow = new PopupWindow(popupLayout, LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
popupWindow.showAtLocation(view, Gravity.CENTER, 0, 0);
}
}
了解popup.xml
中的根元素应该定义background
属性,否则默认情况下窗口是透明的。
答案 1 :(得分:3)
要检查XML布局是否存在问题,您可以尝试以编程方式定义布局
LinearLayout tables = new LinearLayout(getApplicationContext());
for(int i = 0; i < data.length; i++){
ImageView image = new ImageView(getApplicationContext());
try{
int imgID = getResources().getIdentifier(data[i], "drawable", "package");
image.setImageResource(imgID);
}catch(Exception e){
int imgID = getResources().getIdentifier("nia", "drawable", "package");
image.setImageResource(imgID);
}
tables.addView(image);
}
并将此视图添加为ContentView
setContentView(tables);