Android:动态填充GridLayout

时间:2017-05-11 22:28:50

标签: java android android-gridlayout

我正在尝试创建一个活动,其中我有一个动态填充的GridLayout:

这是xml布局:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:gravity="center"
    android:orientation="vertical"
    tools:context="GoalsActivity" >

    <ScrollView
        android:id="@+id/scroll_view"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" >

        <GridLayout
            android:id="@+id/goals_grid"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:columnCount="2"
            android:orientation="horizontal"
            android:layout_gravity="center" >
        </GridLayout>
    </ScrollView>
</LinearLayout>

这是活动:

public class GoalsActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_goals);
        try {
            JSONArray goals = new JSONArray(getIntent().getStringExtra("GOAL_LIST"));
            GridLayout goalsGrid = (GridLayout) findViewById(R.id.goals_grid);

            for(int i = 0; i <= goals.length(); i++) {
                JSONObject goal = goals.getJSONObject(i);
                TextView goalView = new TextView(GoalsActivity.this);
                goalView.setHeight(125);
                goalView.setWidth(125);
                goalView.setText(goal.getString("name"));
                goalsGrid.addView(goalView);
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }
}

正如您所看到的,我正在尝试使用GridLayout显示目标,但每当我运行此代码时,都会发生以下情况:

GirdLayout problem

显然所有TextView都堆叠在一起,但如果我添加其中两个:

<TextView
    android:height="125dp"
    android:width="125dp" /> 
在我的xml布局中手动显示GridLayout下的

,就像我需要它们一样:

Grid size

TextView size

我无法弄清楚如何解决这个问题,非常感谢任何帮助!

0 个答案:

没有答案