Java Android:动态填充GridLayout

Java Android:动态填充GridLayout,java,android,android-gridlayout,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_p

我正在尝试创建一个活动,其中我有一个动态填充的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();
        }
    }
}
public class GoalsActivity扩展了appcompative活动{
@凌驾
创建时受保护的void(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity\u目标);
试一试{
JSONArray goals=newjsonarray(getIntent().getStringExtra(“目标列表”);
GridLayout goalsGrid=(GridLayout)findViewById(R.id.goals\u grid);

对于(int i=0;我只是给出一个建议。你可以使用RecyclerView制作这样的列表。它更强大,更容易解决你的问题,试着将网格布局的宽度设置为
match\u parent
如果我将网格布局的宽度设置为
match\u parent
,文本视图仍然会重叠,只会浮动到t的左侧他打开了屏幕。
<TextView
    android:height="125dp"
    android:width="125dp" />