代码之家  ›  专栏  ›  技术社区  ›  Al Lelopath

设置ListView宽度参数无效

  •  0
  • Al Lelopath  · 技术社区  · 9 年前

    下面带有注释“no effect”的行…没有效果,即宽度未设置为200。ListView将填充屏幕的整个宽度。我做错了什么?

    RelativeLayout relativeLayout = (RelativeLayout) findViewById(R.id.list_alphabet_layout);
    FrameLayout.LayoutParams layoutParams = new FrameLayout.LayoutParams(FrameLayout.LayoutParams.MATCH_PARENT, FrameLayout.LayoutParams.MATCH_PARENT );
    relativeLayout.setLayoutParams(layoutParams);
    
    ListView listView = new ListView(this);
    // the following line as no effect
    listView.setLayoutParams(new ViewGroup.LayoutParams(200, ViewGroup.LayoutParams.MATCH_PARENT)); 
    listView.setFastScrollEnabled(true);
    
    // side index
    LinearLayout sideIndexLinearLayout = new LinearLayout(this);
    sideIndexLinearLayout.setId(R.id.sideIndex);
    
    LinearLayout.LayoutParams sideIndexLinearLayoutParams = new LinearLayout.LayoutParams(100, // width
                                                                                                                                                                                     LinearLayout.LayoutParams.MATCH_PARENT); // height
    sideIndexLinearLayout.setLayoutParams(sideIndexLinearLayoutParams);
    sideIndexLinearLayout.setGravity(Gravity.CENTER_HORIZONTAL);
    sideIndexLinearLayout.setOrientation(LinearLayout.VERTICAL);
    
    // add now so that sideIndexLinearLayout is a child of the RelativeLayout.
    // This will enable us to get the RelativeLayout.LayoutParams to addRule()
    relativeLayout.addView(listView);
    relativeLayout.addView(sideIndexLinearLayout);
    
    RelativeLayout.LayoutParams listViewParams = (RelativeLayout.LayoutParams)listView.getLayoutParams();
    listViewParams.addRule(RelativeLayout.ALIGN_PARENT_LEFT);
    listView.setLayoutParams(listViewParams); //causes layout update
    
    RelativeLayout.LayoutParams sideIndexParams = (RelativeLayout.LayoutParams)sideIndexLinearLayout.getLayoutParams();
    sideIndexParams.addRule(RelativeLayout.ALIGN_PARENT_RIGHT);
    sideIndexLinearLayout.setLayoutParams(sideIndexParams); //causes layout update
    

    XML格式

    <?xml version="1.0" encoding="utf-8"?>
    <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
                    android:id="@+id/list_alphabet_layout"
                    android:layout_width="fill_parent"
                    android:layout_height="fill_parent">
    
    </RelativeLayout>
    
    1 回复  |  直到 9 年前
        1
  •  1
  •   Stefano Vuerich    9 年前

    在这里

    listView.setLayoutParams(new ViewGroup.LayoutParams(200, ViewGroup.LayoutParams.MATCH_PARENT)); 
    listView.setFastScrollEnabled(true);
    

    尝试设置

    listView.setLayoutParams(new RelativeLayout.LayoutParams(200, RelativeLayout.LayoutParams.MATCH_PARENT)); 
    listView.setFastScrollEnabled(true);
    

    相反

    布局参数取决于容器元素。在这种情况下,ListView位于RelativeLayout中,因此需要RelativeLlayout.LayoutParams