以下注释“无效果”的行有...无效,即宽度未设置为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>
答案 0 :(得分:1)
这里
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中,因此您需要RelativeLayout.LayoutParams