如何以编程方式将按钮逐行添加到几行中?

时间:2011-08-25 18:01:55

标签: android button

如何在多行中逐个创建按钮列表? 我做的:

LinearLayout layout = (LinearLayout) findViewById(R.id.linear_layout_tags);
    for (int i = 1; i < 10; i++) {
        Button btnTag = new Button(this);
        btnTag.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
        btnTag.setText("Button " + i);
        btnTag.setId(i);
        layout.addView(btnTag);
        ((Button) findViewById(i)).setOnClickListener(this);
    }

并且只有一行:

I got this
如何以编程方式转到下一行?

5 个答案:

答案 0 :(得分:40)

问题是您的按钮不会自动换行到屏幕的下一部分。您必须具体告诉Android您希望如何定位视图。您可以使用ViewGroups(如LinearLayout或RelativeLayout。

)执行此操作
LinearLayout layout = (LinearLayout) findViewById(R.id.linear_layout_tags);
layout.setOrientation(LinearLayout.VERTICAL);  //Can also be done in xml by android:orientation="vertical"

        for (int i = 0; i < 3; i++) {
        LinearLayout row = new LinearLayout(this);
        row.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT));

        for (int j = 0; j < 4; j++) {
            Button btnTag = new Button(this);
            btnTag.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT));
            btnTag.setText("Button " + (j + 1 + (i * 4)));
            btnTag.setId(j + 1 + (i * 4));
            row.addView(btnTag);
        }

        layout.addView(row);
    }

我假设R.id.linear_layout_tags是此活动的XML的父LinearLayout。

基本上你在这里做的是你正在创建一个LinearLayout,它将是一行来容纳你的四个按钮。然后添加按钮,并为每个按钮增加一个数字作为其ID。添加完所有按钮后,该行将添加到您的活动布局中。然后它重复。这只是一些伪代码,但可能会有效。

哦,下次一定要花更多时间在你的问题上......

https://stackoverflow.com/questions/how-to-ask

答案 1 :(得分:8)

这就像一个答案,但不需要制作XML文件。

public class mainActivity extends Activity {
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        LinearLayout layout = new LinearLayout(this);
        layout.setOrientation(LinearLayout.VERTICAL);  //Can also be done in xml by android:orientation="vertical"

        for (int i = 0; i < 3; i++) {
            LinearLayout row = new LinearLayout(this);
            row.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT));

            for (int j = 0; j < 4; j++) {
                Button btnTag = new Button(this);
                btnTag.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
                btnTag.setText("Button " + (j + 1 + (i * 4 )));
                btnTag.setId(j + 1 + (i * 4));
                row.addView(btnTag);
            }

            layout.addView(row);
        }
        setContentView(layout);
        //setContentView(R.layout.main);
    }
} 

答案 2 :(得分:2)

这将有助于

private void addingParticipantinFrame() {
        TableRow row;
        final int screenWidth = dpToPx(getResources().getConfiguration().screenWidthDp);
        add_button_particiapants.setVisibility(View.VISIBLE);
        if (arrrItemSelcted != null && arrrItemSelcted.size() > 0) {

            arrrItemSelcted.remove(0);
            int i = 0;
            int j = 0;
            int width = (screenWidth - (arrrItemSelcted.size())*4)/arrrItemSelcted.size();

            while (i<arrrItemSelcted.size()) {
                j = i + 4;
                row = new TableRow(mParentActivity);
                TableRow.LayoutParams lp = new TableRow.LayoutParams(TableRow.LayoutParams.MATCH_PARENT, TableRow.LayoutParams.WRAP_CONTENT);
                row.setLayoutParams(lp);
                row.setWeightSum(4);
                while ((i<j)&&(i<arrrItemSelcted.size())) {
                    Button iBtn = new Button(mParentActivity);
                    iBtn.setGravity(Gravity.CENTER_HORIZONTAL);
                    iBtn.setMinimumWidth(100);//I set 100px for minimunWidth.
                    iBtn.setWidth(width);
                    iBtn.setText(Integer.toString(i + 1));
                    iBtn.setId(i + 1);
                    row.addView(iBtn, 4 + i - j);
                    i++;
                }
                add_button_particiapants.addView(row);
            }



            }
        }

答案 3 :(得分:0)

我遇到了问题,即在运行时期间设置了UI的视图数量。所以我决定在一行中只需要四个视图并相应地调整上面的代码。另外,我总是用不可见的编辑文本填充最后一行,以便最后一行中的视图也具有与上面一行中的视图相同的宽度:

        // 1.0f is the weight!
        LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT, 1.0f);
        layoutParams.setMarginEnd(10);

        for (int i = 0; i < Math.ceil(discipline.getSeries_count() / 4.0); i++) {
            LinearLayout layoutRow = new LinearLayout(MyActivity.this);
            layoutRow.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.FILL_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT));

            // add only four edit texts to row and move to next line afterwards
            for (int j = 0; j < 4; j++) {
                etSeries = new EditText(MyActivity.this);
                etSeries.setInputType(InputType.TYPE_CLASS_NUMBER);
                int iIndex = (j + 1 + (i * 4));
                etSeries.setText(getResources().getString(R.string.series) + " " + iIndex);
                etSeries.setId(iIndex);
                etSeries.setId(i);
                etSeries.setSelectAllOnFocus(true);
                etSeries.setLayoutParams(layoutParams);
                etSeries.setVisibility(iIndex > discipline.getSeries_count() ? View.INVISIBLE : View.VISIBLE);
                layoutRow.addView(etSeries);
            }
            layoutSeries.addView(layoutRow);
        }

答案 4 :(得分:0)

最好的方法是使用Google提供的FlexboxLayout。

implementation 'com.google.android:flexbox:1.1.0'
implementation 'androidx.recyclerview:recyclerview:1.0.0'
implementation 'androidx.constraintlayout:constraintlayout:1.1.3'

然后,您必须执行几个步骤。

1)添加一个回收站视图,这是使用flexbox布局映射数据的最佳方法

<androidx.recyclerview.widget.RecyclerView
        android:id="@+id/recycler_view"
        android:layout_width="match_parent"
        android:layout_height="0dp" />

2)然后提供您自己的适配器

public class LinkedListAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder>{


        private final LayoutInflater mInflater;
        private List<String> mItems = Collections.emptyList();



    LinkedListAdapter(Context context) {
        mInflater = LayoutInflater.from(context);
    }

    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View itemView = mInflater.inflate(R.layout.my_layout_item, parent, false);
        return new ViewHolder(itemView);
    }

    @Override
    public void onBindViewHolder(@NonNull RecyclerView.ViewHolder holder, int position) {
        ((ViewHolder)holder).updateWithItem(this.mItems.get(position), this.callback);
    }

    @Override
    public int getItemCount() {
        return mItems.size();
    }

    void setItems(List<String> items){
        mItems = items;
        notifyDataSetChanged();
    }

    class ViewHolder extends RecyclerView.ViewHolder{

        private final TextView itemText;

        private ViewHolder(View view) {
            super(view);
            itemText = view.findViewById(R.id.item);
        }

        public void updateWithItem(String item){
            itemText.setText(item);
        }

    }

    public List<String> getItems() {
        return mItems;
    }

}

3)如您现在所见,您应该有一些定义布局的内容,my_layout_item.xml应该放在布局文件夹中

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content">

    <TextView
        android:id="@+id/item"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Hello World!"
        android:padding="15dp"
        android:layout_margin="5dp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent"/>

</androidx.constraintlayout.widget.ConstraintLayout>

4)现在,在片段或活动中,您必须链接所有这些东西。

myReclyclerView = view.findViewById(R.id.recycler_view);

FlexboxLayoutManager flexboxLayoutManager = new FlexboxLayoutManager(getActivity());
flexboxLayoutManager.setFlexDirection(FlexDirection.ROW);
flexboxLayoutManager.setJustifyContent(JustifyContent.CENTER);
flexboxLayoutManager.setFlexWrap(FlexWrap.WRAP);
myReclyclerView .setLayoutManager(flexboxLayoutManager);

List<String> items = new ArrayList<String>();
items.add("test");
myAdapter = new LinkedListAdapter (getContext());
myReclyclerView.setAdapter(myAdapter);
myAdapter.setItems(items);

在这里,这对我来说是最好的解决方案。

科特林(Kotlin)的来源:https://medium.com/gett-engineering/android-div-like-flexbox-layout-55f0e1286d66