如何以编程方式在 android 的布局中添加新按钮

How to add a new button in layout of the android programmatically

我有一个布局,其中有 3 个文件夹和一个添加按钮。
我想要的是当用户点击添加按钮时。一个新的文件夹被添加到添加按钮位置的布局中,添加按钮向下移动到 folder-3.
关于如何创建此动态布局的任何建议。目前我什至没有一个可以实现它的骇人听闻的想法。


非常感谢任何帮助。 谢谢你。

使用 button = new Button(getApplicationContext()) 创建按钮,然后使用 layout = (LinearLayout) findViewById (R.id.<yourLayoutId>) 获取您的 viewGroup 对象(我猜是 LinearLayout),然后仅 layout.addView(button).

//the layout on which you are working
LinearLayout layout = (LinearLayout) findViewById(R.id.linear_layout_tags);

//set the properties for button
Button btnTag = new Button(this);
btnTag.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
btnTag.setText("Button");
btnTag.setId(some_random_id);

//add button to the layout
layout.addView(btnTag);

试试这个:

LinearLayout layout = new LinearLayout(context);
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
            LinearLayout.LayoutParams.WRAP_CONTENT,
            LinearLayout.LayoutParams.MATCH_PARENT);
Button btn = new Button(this); 
btn .setLayoutParams(params);
layout.addView(btn);

使用带有自定义适配器的 GridView

<?xml version="1.0" encoding="utf-8"?>
<GridView xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/gridview"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:columnWidth="90dp"
    android:numColumns="auto_fit"
    android:verticalSpacing="10dp"
    android:horizontalSpacing="10dp"
    android:stretchMode="columnWidth"
    android:gravity="center" />

您将需要一个自定义适配器来扩充网格视图。 保留一个计数器,比如 nbFolders 代表文件夹的数量。

int nbFolders = 0;

public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    GridView gridview = (GridView) findViewById(R.id.gridview);
    gridview.setAdapter(new FolderAdapter());

    gridview.setOnItemClickListener(new OnItemClickListener() {
        public void onItemClick(AdapterView<?> parent, View v,
                int position, long id) {
            if(position == nbFolders){
                nbFolders++;
                ((FolderAdapter)gridView.getAdapter()).notifyDataSetChanged();
            }
        }
    });
}

//Here is where the magic happens
public class FolderAdapter extends BaseAdapter {

    public int getCount() {
        return nbFolders + 1;
    }

    public View getView(int position, View convertView, ViewGroup parent) {
        TextView yourView;
        if (convertView == null) {
           yourView = new TextView(YourActivity.this);
        } else {
            yourView = (TextView) convertView;
        }

        if(position < nbFolders){
            yourView.setText("Folder " + (position + 1));
        }else{
            yourView.setText("Add");
        }

        return yourView;
    }

}