我正在尝试设置我的LinearLayout代码端的宽度。 我正在尝试找到一种方法,可以将我的 IcsSpinner 的所选导航项调整为所选项目大小......当我将 xml 中的线性布局设置为一定宽度时,这是实现的......但我需要动态大小。
<LinearLayout
android:id="@+id/spinner_ll"
android:layout_width="75dp"
android:layout_height="wrap_content"
android:layout_gravity="right" >
<com.actionbarsherlock.internal.widget.IcsSpinner
android:id="@+id/spinner"
android:layout_width="match_parent"
android:layout_height="match_parent"
/>
</LinearLayout>
有没有办法设置线性布局的宽度,而不是子布局的宽度?
更新。。。答:
LinearLayout.LayoutParams lp = (LinearLayout.LayoutParams)ll.getLayoutParams();
lp.width = 85; // set this to size...this is arbitrary number for proof of concept
ll.requestLayout();
您可以从代码中设置布局参数,如下所示:
LinearLayout layout = (LinearLayout) findViewById(R.id.spinner_11);
LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(100 /* in pixels */, LayoutParams.WRAP_CONTENT);
layout.setLayoutParams(layoutParams);
您可以在代码中将 dps 转换为像素,如下所示:
int pixelValue = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 10 /* in dps */, getResources().getDisplayMetrics());
看看这里的文档:https://developer.android.com/reference/android/util/TypedValue.html#applyDimension(int, float, android.util.DisplayMetrics)