0

每次我动态地将图像视图添加到我的线性布局时,我都会得到一个空指针异常。

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 if

4

2 回答 2

3

如果这是导致空指针异常的行:

tables.addView(image);

thentables为 null,简单地 findViewById() 没有R.id.table在当前显示的布局中找到任何具有 id 的 View。

(如果您需要帮助找出为什么tables为空,请发布您传递给的布局setContentView()

从评论中添加

这是创建 PopupWindow 的一般方法。这使用 LayoutInflator 来膨胀布局,以便我们可以访问它以动态地将元素添加到布局中。(请注意,我们将 find 范围限定为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定义一个属性,否则默认情况下窗口是透明的。

于 2012-07-10T20:01:51.613 回答
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);
于 2012-07-10T20:41:24.233 回答