0

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

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;
        }
    }

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

4

2 回答 2

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;
        }
    }   
}
于 2012-04-26T23:11:30.590 回答
0

当你第一次创建 LinearLayout 时,给它一个 id。然后你可以用 findViewById() 第二次得到它。要回答您的第二个问题,请在SharedPreferences中存储一个布尔值。

于 2012-04-26T22:51:35.513 回答