【问题标题】:Programmatically create rows with linearlayouts in Android在 Android 中以编程方式创建具有线性布局的行
【发布时间】:2015-10-23 00:59:51
【问题描述】:

我可能会以错误的方式进行此操作,但我的代码几乎就在那里,所以我认为我离得太远了。我正在尝试以编程方式创建带有两个垂直线性布局的水平线性布局。我已经在 xml 中创建了它来测试它,但是当我从 db 加载数据时,我需要动态创建行。

这是我的 xml 的外观以及我尝试以编程方式创建的内容:

<LinearLayout
        android:orientation="horizontal"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:baselineAligned="false">

        <LinearLayout
            android:orientation="vertical"
            android:layout_width="0dp"
            android:layout_weight="1"
            android:layout_height="match_parent"
            android:layout_marginLeft="25dip"
            android:layout_marginRight="10dip"
            android:background="@drawable/rounded_edges_white">

            <ImageView
                android:layout_width="120dp"
                android:layout_height="80dp"
                android:id="@+id/imageView3"
                android:contentDescription="personIcon"
                android:src="@drawable/person_icon"
                android:layout_gravity="center" />
            <View
                android:layout_width="match_parent"
                android:layout_height="1dp"
                android:background="#f1f1f1"
                android:layout_marginBottom="10dip" />

            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="Danielle"
                android:id="@+id/textView81"
                android:layout_gravity="center_horizontal" />
        </LinearLayout>

        <LinearLayout
            android:orientation="vertical"
            android:layout_width="0dp"
            android:layout_weight="1"
            android:layout_height="fill_parent"
            android:layout_marginLeft="10dip"
            android:layout_marginRight="25dip"
            android:background="@drawable/rounded_edges_white">

            <ImageView
                android:layout_width="120dp"
                android:layout_height="80dp"
                android:id="@+id/imageView2"
                android:contentDescription="personIcon"
                android:src="@drawable/person_icon"
                android:layout_gravity="center" />
            <View
                android:layout_width="match_parent"
                android:layout_height="1dp"
                android:background="#f1f1f1"
                android:layout_marginBottom="10dip" />

            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="Danielle"
                android:id="@+id/textView8"
                android:layout_gravity="center_horizontal" />
        </LinearLayout>
    </LinearLayout>

所以我可以复制那个 xml 来获得我想要的布局。这是我创建的代码:

    public void buildHome(){
        DatabaseHandler db = new DatabaseHandler(this);
        List<Person> people = db.getAllPeople();

        LinearLayout parentLayout = (LinearLayout) this.findViewById(R.id.personList);\
        float padding25 = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 25, getResources().getDisplayMetrics());
        float padding10 = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 10, getResources().getDisplayMetrics());
        float size120 = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 120, getResources().getDisplayMetrics());
        float size80 = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 80, getResources().getDisplayMetrics());
        float size = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 1, getResources().getDisplayMetrics());
        float mBottom = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 15, getResources().getDisplayMetrics());


        int count = 0;
        int totalCount = 1;
        LinearLayout rowLayout = null;
        LinearLayout childLayout = null;
        for (final Person peep : people) {
            if(count == 2) count = 0;
            Log.d("count", ""+count);
            if(count == 0) {
                Log.d("creating row", "true");
                //create row layout container
                rowLayout = new LinearLayout(this);
                rowLayout.setOrientation(LinearLayout.HORIZONTAL);
                LinearLayout.LayoutParams rowParams = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
                rowLayout.setTag(totalCount);
                rowLayout.setLayoutParams(rowParams);
                rowLayout.setBaselineAligned(false);
            }

            //create row layout container
            childLayout = new LinearLayout(this);
            childLayout.setOrientation(LinearLayout.VERTICAL);
            LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.MATCH_PARENT, 1f);

            //left or right col
            if(count == 0) layoutParams.setMargins(Math.round(padding25), Math.round(padding10), Math.round(padding10), 0);
            else layoutParams.setMargins(Math.round(padding10), Math.round(padding10), Math.round(padding25), 0);
            childLayout.setLayoutParams(layoutParams);

            childLayout.setTag(peep.getId());
            childLayout.setClickable(true);
            childLayout.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(Main.this);
                    SharedPreferences.Editor editor = preferences.edit();
                    editor.putString("personID", "" + peep.getId());
                    editor.apply();

                    Intent intent = new Intent(Main.this, List.class);
                    startActivityForResult(intent, 1);
                }
            });
            childLayout.setBackgroundResource(R.drawable.rounded_edges_white);

            //set icon
            ImageView icon = new ImageView(this);
            LinearLayout.LayoutParams imageParams = new LinearLayout.LayoutParams(Math.round(size120), Math.round(size80));
            imageParams.gravity = Gravity.CENTER_HORIZONTAL;
            icon.setLayoutParams(imageParams);
            icon.setContentDescription("personIcon");
            icon.setImageResource(R.drawable.person_icon);
            childLayout.addView(icon);

            //horizontal line
            View horizontalLine = new View(this);
            horizontalLine.setBackgroundColor(Color.LTGRAY);
            LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, Math.round(size));
            params.setMargins(0, 0 , 0, Math.round(mBottom));
            horizontalLine.setLayoutParams(params);
            childLayout.addView(horizontalLine);

            //Set name title
            TextView titleView = new TextView(this);
            titleView.setText(peep.getName());
            LinearLayout.LayoutParams titleParams = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
            titleParams.gravity = Gravity.CENTER_HORIZONTAL;
            titleView.setLayoutParams(titleParams);
            childLayout.addView(titleView);

            //add to row
            rowLayout.addView(childLayout);

            //add to parent view
            if(count == 1){
                Log.d("add to parent", "true");
                parentLayout.addView(rowLayout);
            }
            count++;
            totalCount++;
        }

        Log.d("size", ""+people.size());
        if(people.size() % 2 != 0) {
            Log.d("only 1", "true");
            parentLayout.addView(rowLayout);
        }
    }

日志是这样写的:

10-21 17:48:41.586 24022-24022/com.example.app D/count: 0
10-21 17:48:41.586 24022-24022/com.example.app D/creating row: true
10-21 17:48:41.587 24022-24022/com.example.app D/count: 1
10-21 17:48:41.598 24022-24022/com.example.app D/add to parent: true
10-21 17:48:41.598 24022-24022/com.example.app D/count: 0
10-21 17:48:41.598 24022-24022/com.example.app D/creating row: true
10-21 17:48:41.598 24022-24022/com.example.app D/after the first row: true
10-21 17:48:41.599 24022-24022/com.example.app D/count: 1
10-21 17:48:41.599 24022-24022/com.example.app D/add to parent: true
10-21 17:48:41.600 24022-24022/com.example.app D/size: 4

所以它打到了所有正确的地方,并说它正在创建行并添加到父级。这是最接近我正在做的事情linear layout inside linear layout is adding but is not visible

但他并没有真正动态地添加额外的行。如果他过去,他有 layout2 和 3。

这就是我的目标(根据需要重复多次):

            |---------------|   |---------------|
            |               |   |               |
            |               |   |               |
            |               |   |               |
            |               |   |               |
            |---------------|   |---------------|

            |---------------|   |---------------|
            |               |   |               |
            |               |   |               |
            |               |   |               |
            |               |   |               |
            |---------------|   |---------------|

我在数据库中有 4 个项目,但只有第 1 行有 2 个项目显示。

谢谢

【问题讨论】:

  • 实际上,即使您从数据库中提取数据,也不需要动态创建布局。您可以使用自定义列表视图非常整齐地显示您的数据库数据。
  • 我有兴趣,我该怎么做?
  • 您可以查看使用自定义对象制作 CustomListViews 的教程。由于您想要每行 2 列,我建议您执行 GridView 并将列数指定为 2。制作自定义 GridView 与制作自定义列表视图非常相似。稍后我会尝试写一个例子,我只需要检查我的代码。
  • 我在查找我的代码时似乎遇到了麻烦。 :/ 您可以尝试在 Google 上搜索如何进行自定义 GridViews,我相信您会找到使用自定义对象(反映您的数据库条目)以及自定义 gridView 适配器的示例。
  • 在试图弄清楚这一点时,我看到了一些 gridview 的东西,我会看看我是否能弄清楚

标签: android android-linearlayout


【解决方案1】:

这与你的代码有关

//add to parent view
if(count == 1){
  Log.d("add to parent", "true");
     parentLayout.addView(rowLayout);
  }
 count++;
 totalCount++;

你应该改成

if(count % 2 == 1) {

这将每 2 项添加一行

【讨论】:

  • 当我将其更改为 if(count %= 1) 时,它表示需要布尔值。我的日志文件显示它每 2 次创建一行。
  • 对不起,该行应该是 if (count % 2 == 1)
  • 这和我之前的一样。无论哪种方式,它都会进入第二行的代码,第二行只是没有显示。我在那里放了一个 log.d 以确保它在 if 语句中。我觉得它正在添加它,但是这些项目是不可见的或只是不显示??
  • 你应该删除 if(count == 2) count = 0;
  • 但这不是问题。 if(count % 2 == 1) 中的代码在正确的时间运行。见我上面的日志。 Log.d("添加到父级", "true");以正确的顺序运行两次。我删除了 if(count ==2) count =0;当它已经有一个父母时,它在添加孩子时会出错。
猜你喜欢
  • 2017-12-25
  • 2013-06-28
  • 2012-08-07
  • 2018-10-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多