为什么我动态添加的ListView到LinearLayout无法正常显示?

时间:2017-05-10 15:19:43

标签: android android-layout listview

我正在向{vertical} ListView动态添加LinearLayout布局。但是,当应用程序运行时,所有数据都会在屏幕上挤压在一起。如果我尝试滚动,我发现每个独立的ListView都是可滚动的,我每次ListView只能看到一行,而不是我可以滚动的LinearLayout

这就是我所拥有的:

MainActivity.java

public class MainActivity extends AppCompatActivity {
    @Override
    protected void onCreate(){
        super.onCreate();
        setContentView();

        printSensors();
    }

    private void printSensors(){
        SensorManager sensorManager = (SensorManager) getSystemService(SENSOR_SERVICE);
        ListView.LayoutParams layoutParams = new ListView.LayoutParams(ListView.LayoutParams.MATCH_PARENT, ListView.LayoutParams.WRAP_CONTENT);

        LinearLayout mainLayout = (LinearLayout)findViewById(R.id.main_layout);
        List<Sensor> sensorList = sensorManager.getSensorList(Sensor.TYPE_ALL);

        for(Sensor sensor : sensorList){
            ListView listView = new ListView(this);
            listView.setId(View.generateViewId());
            listView.setLayoutParams(layoutParams);

            String[] sensorArray = sensor.toString().substring(1, sensor.toString().length()-1).split(",");
            ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, sensorArray);

            listView.setAdapter(arrayAdapter);
            mainLayout.addView(listView);
        }
    }
}

activity_main.xml中

<ScrollView>
    <LinearLayout android:id="@+id/main_layout" android:orientation="vertical">
    </LinearLayout>
</ScrollView>

但是,如果我将ListView.LayoutParams.WRAP_CONTENT更改为整数,例如500,那么所有内容都很好地展示并且看起来不错。

那么,是什么给出了?

3 个答案:

答案 0 :(得分:0)

更改listView的宽度以匹配父级而不是换行内容,还必须设置高度和宽度以滚动视图

答案 1 :(得分:0)

private void printSensors(){
    list = (ListView) findViewById(R.id.list);
    ArrayList<String> sensorArray = new ArrayList<>();
    SensorManager sensorManager = (SensorManager) getSystemService(SENSOR_SERVICE);
    List<Sensor> sensorList = sensorManager.getSensorList(Sensor.TYPE_ALL);
    for(Sensor sensor : sensorList){
        sensorArray.add(sensor.toString().substring(1, sensor.toString().length()-1).split(",").toString());
    }
    ArrayAdapter<String> arrayAdapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, sensorArray);
    list.setAdapter(arrayAdapter);
}

答案 2 :(得分:0)

将LinearLayout包装在另一个LinearLayout中,如下所示:

<ScrollView>
  <LinearLayout android:orientation="vertical">
    <LinearLayout  android:id="@+id/main_layout"
     android:orientation="vertical">
    </LinearLayout>
  </LinearLayout>
</ScrollView>