【问题标题】:How do I programmatically add buttons into layout one by one in several lines?如何以编程方式将按钮逐行添加到布局中?
【发布时间】:2011-11-03 22:26:33
【问题描述】:

如何逐行创建按钮列表? 我做的:

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

只有一行:


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

【问题讨论】:

  • 我的第一个想法是为 ListView 更改自定义 SimpleCursorAdapter 中的 getView(),但以编程方式放置按钮可能更简单。所以,我在这里问。可能有人决定了这个问题。
  • 我可以为你回答这个问题,但问题已结束:/
  • 太糟糕了 android 不支持这个开箱即用。我认为像 CSS inline-block 这样的东西在 android 中会非常有用。

标签: android button


【解决方案1】:

问题是您的按钮不会自动换行到屏幕的下一部分。您必须明确告诉 Android 您希望如何定位视图。您可以使用诸如 LinearLayout 或 RelativeLayout 之类的 ViewGroups 来执行此操作。

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

【讨论】:

  • 当我们知道 3 个按钮总是排成一行时,这段代码很好。但是当按钮中的文本取自Cursor(来自数据库)时该怎么办?按钮的宽度可以是这样,只有两个按钮可以排成一行。所以第三个按钮必须在下一行。以及单击它时如何删除某些按钮。可能我必须为此更改自定义SimpleCursorAdapter 中的getView()。我想要这样的东西:link
  • 感谢您的示例!我建议通过 LayoutParams.MATCH_PARENT 更改 LayoutParams.FILL_PARENT
【解决方案2】:

这就像 1 个答案,但不需要制作 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);
    }
} 

【讨论】:

  • 谢谢,很高兴知道有人以编程方式理解。
  • 非常感谢! +1 设置内容视图(布局)
【解决方案3】:

这会有所帮助

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



            }
        }

【讨论】:

    【解决方案4】:

    最好的方法是使用 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

    【讨论】:

    • 是的,FlexboxLayout 无需编码即可完成这项工作。
    【解决方案5】:

    我遇到了问题,要放置在 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);
            }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-05-03
      • 1970-01-01
      • 2014-03-30
      • 1970-01-01
      • 2020-10-22
      • 2014-04-26
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多