如何动态添加按钮

时间:2012-04-26 22:21:54

标签: android android-widget

我想让用户添加按钮 这样每行只有四个按钮。  所以我写了以下函数:

private void addContact() {
        //numButton Count how many buttons there are in line
        if(numButton==0){
            LinearLayout linearLayout =new LinearLayout(this);
            linearLayout.setOrientation(0);//horizontal
            ImageButton imageButton =new ImageButton(this);
            imageButton.setImageBitmap(BitmapFactory.decodeResource(getResources(), R.drawable.button1));
            linearLayout.addView(imageButton);
            LinearLayout linearbase= (LinearLayout)findViewById(R.id.linearBase);
            linearbase.addView(linearLayout);
            numButton++;
        }
        else if(numButton<4)
        {
            LinearLayout linearlayout= ----####Here I do not know what to write!!!!###
            ImageButton imageButton =new ImageButton(this);
            imageButton.setImageBitmap(BitmapFactory.decodeResource(getResources(), R.drawable.button1));
            linearlayout.addView(imageButton);
            numButton++;
        }
        else 
        {
            numButton=0;
        }
    }

我标记了代码行我的问题 具体来说,我的问题是如何将新按钮放入上一次调用此函数中定义的linearlayout中? 第二个问题:即使关闭应用程序,如何保持新的情况?

2 个答案:

答案 0 :(得分:0)

第一次创建LinearLayout时,请为其指定ID。然后你可以用findViewById()第二次得到它。要回答第二个问题,请在SharedPreferences中存储布尔值。

答案 1 :(得分:0)

在addContact方法之外声明LinearLayouts,否则它们只存在于该方法中。我认为这样的应该有效(我还没有测试过):

class myclass{

    private LinearLayout linearLayout;
    private LinearLayout linearbase;
    private int numButton;

    @Override
    public void onFinishInflate() {
        super.onFinishInflate();

        linearbase= (LinearLayout)findViewById(R.id.linearBase);
        LinearLayout linearLayout =new LinearLayout(this);
        linearLayout.setOrientation(0);//horizontal

        numButton=0;
    }

    private void addContact() {
        //numButton Count how many buttons there are in line
        if(numButton==0){

            ImageButton imageButton =new ImageButton(this);
            imageButton.setImageBitmap(BitmapFactory.decodeResource(getResources(), R.drawable.button1));
            linearLayout.addView(imageButton);
            linearbase.addView(linearLayout);
            numButton++;
        }
        else if(numButton<4)
        {
            linearLayout= new LinearLayout(this);
            ImageButton imageButton =new ImageButton(this);
            imageButton.setImageBitmap(BitmapFactory.decodeResource(getResources(), R.drawable.button1));
            linearlayout.addView(imageButton);
            numButton++;
        }
        else 
        {
            numButton=0;
        }
    }   
}