Android:删除以编程方式添加带ID的图像按钮

时间:2015-03-21 20:59:53

标签: android android-layout android-intent android-gridlayout android-imagebutton

它会怎么样?我正在为一个项目创建一个小小的培训应用程序,除了格式化问题之外它还可以。所以,我有一个csv文件,其中包含客户端的名称和年龄。从这里创建一个数组,然后我有一个包含网格布局的滚动视图,我从客户端数组创建图像按钮。这一切都很好。我在这个结尾处有一个添加客户端按钮,按钮和它的活动工作正常,但是当你回到主屏幕时,按钮都被搞砸了(巨大的,错位的等)。所以我想我会循环并删除所有按钮并重新填充主屏幕,除了,因为我以编程方式创建它们,我无法弄清楚如何找到它们删除它们。我尝试将他们的id设置为数组的索引,但后来我得到一个空指针错误。

创建按钮的功能:

public void fillActivity_main(){
    if(listPopulated == false) { // check to see if its aready been created
        populateClientList();//fill array with client objects
        listPopulated = true;
    }
    //setup asset manager
    AssetManager am = getApplicationContext().getAssets();

    //Create the "GridLayout Image Board"
    GridLayout buttonBoard = (GridLayout) findViewById(R.id.buttonboard);
    int idealWidth = buttonBoard.getWidth(); //get width of the board
    int idealHeight = buttonBoard.getHeight() / 2;//same

    //create the Listeners, this is a place holder for now but will eventually use SetCurrentClient() (or maybe just switch to Start screen, with the current client?)
    View.OnClickListener imageClickListener = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            System.out.println("CLICK AT: " + v.getId());
            Client temp = clientList[v.getId()];

            Intent i = new Intent(getApplicationContext(), DisplayClient.class);
            System.out.println(temp.getName());
            i.putExtra("name", temp.getName());
            System.out.println(i.getStringExtra("name"));
            i.putExtra("age", Integer.toString(temp.getAge()));
            startActivity(i);

        }
    };
    int j = 0; //used the keep track of the id's we set for the buttons
    for (int i = 0; i < clientList.length; i++) {
        if (clientList[i] != null) {
            //creation and ID setting
            ImageButton imgbutton = (ImageButton) new ImageButton(this);
            imgbutton.setId(i);

            //Layout shit
            imgbutton.setImageResource(R.mipmap.ic_launcher);
            imgbutton.setMinimumWidth(idealWidth);
            imgbutton.setMinimumHeight(idealHeight);

            imgbutton.setOnClickListener(imageClickListener);


            //check and set image
            if(clientList[i].getClientImage().equals(" ")) {
                try{
                    imgbutton.set(am.openFd(clientList[i].getClientImage()));}
                    catch(Exception ex){
                         ex.toString();
               }
                Log.d("ClientImageCheck", "No picture found for " + clientList[i].getName());
            }
            buttonBoard.addView(imgbutton);
            j++;
        }


    }
    //create the new Client Button at the end of all the rest.
    Button newClientButton = (Button) new Button(this);
    newClientButton.setText("+");  // obvious
    newClientButton.setLayoutParams(new LinearLayout.LayoutParams(GridLayout.LayoutParams.WRAP_CONTENT, GridLayout.LayoutParams.WRAP_CONTENT));
    newClientButton.setWidth(idealWidth);
    newClientButton.setHeight(idealHeight);
    View.OnClickListener newClientListener = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Intent i = new Intent(getApplicationContext(), CreateClientForm.class);
            startActivityForResult(i, 199);
            //System.out.println("Doing good so far, leaving the createclient form bnut still in main");

        }
    }; // create listener
    newClientButton.setOnClickListener(newClientListener); // assign listener
    buttonBoard.addView(newClientButton); //add the button the buttonBoard, after all the clients have been added
}

我执行删除的功能:

protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    //Check which request we're responding to
    if (requestCode == 199) {
        // Make sure request was successful
        if (resultCode == RESULT_OK) { 
            // The user made a name and crap.
            Bundle extras = data.getExtras();
            String name = extras.getString("name");
            int age = extras.getInt("age");



            Client temp = new Client(name, age);
            addClientToArray(temp);
            System.out.println(name + "attempted add to array");

        }
    for(int i = 0; i<clientList.length; i++ ){
        View v = findViewById(i);
        ((ViewManager) v.getParent()).removeView(v);
    }
    fillActivityMain();
}

如果我的逻辑正确,循环中的'i'应该是合适的id。当然,教学有点让我们深入到这个项目,从来没有采用移动应用程序或任何东西,所以所有这些代码是我搜索问题的结果,因为我遇到它们。我已经阅读了视图,意图等的基础知识,但必须有一些我缺少的东西。

我已经尝试制作gridLayout,按钮位于类变量上,所以我可以将其称为buttonBoard.removeView(i)或其他东西。 香港专业教育学院也尝试过`

for(int i = 0; i<clientList.length; i++ ){
  ImageButton btn = (ImageButton) findViewByid(i);
  ((ViewManager) v.getParent()).removeView(btn);
}

2 个答案:

答案 0 :(得分:0)

您可以在删除现有图像的同时添加替换图像吗?如果是这样,试试这个:

for(int i = 0; i < buttonBoard.getChildCount(); i++) {
ImageButton tempButton = (ImageButton) buttonBoard.getChildAt(i);
tempButton.setVisibility(View.INVISIBLE);
buttonBoard.addView(yourImageButtonHere, i); //adds a new ImageButton in the same cell you are removing the old button from
buttonBoard.removeView(tempButton);
}

这种方法还应该阻止GridLayout重新排列子项所在的位置。我相信如果删除子视图,默认行为是GridLayout将重新排序子节点,因此网格开头没有空单元格。我希望这是有道理的。

答案 1 :(得分:0)

这种方法存在很多错误。

主要是您不必手动创建ImageButtons并将其添加到GridLayout。这就是GridViewRecyclerView等回收视图的用途。实际上,您应该使用这些来避免OutOfMemoryError在您的布局中包含太多图像。

但你也不能只在for循环中调用setId(i)。 Android拥有许多已分配的ID,您永远无法确定该ID是否安全。 (除非您使用View.generatViewId()

由于您只想删除添加到GridLayout的所有视图,为什么不在buttonBoard上调用removeAllViews()