Hi android developers,Android: Как установить Item ListView в процентах?
Я новичок в разработке Android, и теперь я программирую свое первое приложение для Android. Однако у меня есть одна проблема, которую я не могу понять.
Ситуация: Я реализовал ListFragment и ItemAdapter расширяет ArrayAdapter. Этот адаптер возвращает всегда пять элементов или меньше, когда пользователь нажимает на кнопку из фрагмента.
Вопрос в том, как установить высоту элемента на 20% родительского элемента? Я попытался установить layout_weight в 20 элементов макета с layout_height = "0dp", но это не решило мою проблему. Если установить высоту в процентах не представляется возможным, могу ли я получить высоту родительского элемента и установить высоту элемента программно?
фрагмент XML:
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_height="match_parent"
android:layout_width="match_parent"
android:background="@color/grey_light"
tools:context=".Fragment" >
<ListView
android:id="@android:id/list"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginBottom="@dimen/footer"
android:isScrollContainer="false">
</ListView>
<RelativeLayout
android:id="@+id/footer"
android:layout_gravity="bottom"
style="@style/footer" >
<Button
android:id="@+id/btn_next"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:text="@string/button.next"
android:textSize="@dimen/text_bigger"
android:textColor="@color/white"
android:drawableRight="@drawable/ic_chevron_white"
android:background="@android:color/transparent" />
</RelativeLayout>
</FrameLayout>
Фрагмент класса onActivityCreated метод:
@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
MyActivity activity = (MyActivity)getActivity();
ItemAdapter adapter = new ItemAdapter (getActivity(), activity.getNextItems(5));
setListAdapter(adapter);
}
Item XML:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/layout"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="20"
android:orientation="horizontal"
android:descendantFocusability="blocksDescendants">
<RelativeLayout
android:layout_weight="80"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:gravity="center_vertical">
<TextView
android:id="@+id/txtV_order"
android:text="@+id/txt_order"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:textColor="?darkColor"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
</TextView>
<TextView
android:id="@+id/txtV_text"
android:text="@+id/txt_text"
android:layout_alignParentTop="true"
android:layout_toRightOf="@+id/txtV_order"
android:layout_marginLeft="24dp"
android:textColor="?darkColor"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
</TextView>
</RelativeLayout>
<RelativeLayout
android:layout_weight="20"
android:layout_width="0dp"
android:layout_height="match_parent"
android:padding="@dimen/standard_padding">
<ToggleButton
android:id="@+id/btn_toggle"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:backgroud="@drawable/toggle"
android:layout_centerInParent="true" />
</RelativeLayout>
</LinearLayout>
ItemAdapter метод класса GetView:
@Override
public View getView(final int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View rowView = inflater.inflate(R.layout.item, parent, false);
TextView textView = (TextView) rowView.findViewById(R.id.txtV_order);
textView.setText(Integer.toString(position + 1));
textView = (TextView) rowView.findViewById(R.id.txtV_text);
textView.setText(item[position].getText());
ToggleButton btn = (ToggleButton) rowView.findViewById(R.id.btn_toggle);
//if true - set checked if false - set unchecked
btn.setChecked(item[position].isChecked());
onToggleBtnClick(btn, position);
return rowView;
}
РЕШЕНИЕ:
Мой Util класс:
public class Utils {
//get status bar height
public static int getStatusBarHeight(Activity activity) {
int result = 0;
int resourceId = activity.getResources().getIdentifier("status_bar_height", "dimen", "android");
if (resourceId > 0) {
result = activity.getResources().getDimensionPixelSize(resourceId);
}
return result;
}
//get action/title bar height
public static int getActionBarHeight(Activity activity) {
Rect rect= new Rect();
Window window= activity.getWindow();
window.getDecorView().getWindowVisibleDisplayFrame(rect);
int statusBarHeight= rect.top;
int contentViewTop= window.findViewById(Window.ID_ANDROID_CONTENT).getTop();
return contentViewTop - statusBarHeight;
}
//get screen height with bars
public static int getScreenHeight(Activity activity) {
WindowManager wm = (WindowManager) activity.getSystemService(Context.WINDOW_SERVICE);
Display display = wm.getDefaultDisplay();
Point size = new Point();
display.getSize(size);
int height = size.y;
return height;
}
//get height of layout...
public static int getLayoutHeight(Activity activity) {
return getScreenHeight(activity) - getActionBarHeight(activity) - getStatusBarHeight(activity);
}
}
В классе ItemAdapter:
View rowView = inflater.inflate(R.layout.item, parent, false);
int numberOfItems = 5;
int itemHeight = (int)(Utils.getLayoutHeight(context)/numberOfItems);
rowView.setMinimumHeight(itemHeight);
Это не то, как layout_weight работает. Вес - это соотношение, основанное на всех других весах. Например, три вида с весами 2, 1, 1 соответственно приведут к тому, что высота (или ширина) первого вида будет в два раза выше, чем у второй или третьей. Имеет ли это смысл? – hungryghost
Проверьте это http://stackoverflow.com/a/16518557/1939564 –