如果视图宽度固定,我想计算一次在屏幕上显示多少视图。为此,我得到一个布局,在其中添加一些固定大小的视图并运行它。
但是根据我的计算,我在屏幕上显示的孩子数量错误,因为它显示在屏幕上。
请告诉我我错在哪里?
这是我的代码...
In Activity ...
----
LinearLayout featured_listlayout_horizontallayout=(LinearLayout)findViewById(R.id.featured_listlayout_horizontallayout);
LayoutInflater inflater=LayoutInflater.from(getApplicationContext());
for(int i=0;i<20;i++){
LinearLayout childItem=(LinearLayout)inflater.inflate(R.layout.childitemlayout,null);
Button btn=(Button)childItem.findViewById(R.id.btn);
btn.setText("Item"+(i+1));
featured_listlayout_horizontallayout.addView(childItem);
}
DisplayMetrics dm = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(dm);
final int height = dm.heightPixels;
float screenWidth = dm.widthPixels;//Screen Width in pixel
float itemWidth=getResources().getDimension(R.dimen.featured_text);//itemWidth in DP
itemWidth=convertDpToPixel(itemWidth, getApplicationContext());// convert itemWidth into pixel
System.out.println("screenWidth "+screenWidth+" itemWidth "+itemWidth);
float noOfItem=screenWidth/itemWidth;
System.out.println("noOfItem "+noOfItem);
-----
convertPixelsToDp method:
public float convertPixelsToDp(float px,Context context){
Resources resources = context.getResources();
DisplayMetrics metrics = resources.getDisplayMetrics();
float dp = px / (metrics.densityDpi / 160f);
return dp;
}
convertDpToPixel method:
public float convertDpToPixel(float dp,Context context){
Resources resources = context.getResources();
DisplayMetrics metrics = resources.getDisplayMetrics();
float px = dp * (metrics.densityDpi/160f);
return px;
}
activity_main.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity" >
<HorizontalScrollView
android:layout_width="match_parent"
android:layout_height="wrap_content" >
<LinearLayout
android:id="@+id/featured_listlayout_horizontallayout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:paddingBottom="5dp" >
</LinearLayout>
</HorizontalScrollView>
</RelativeLayout>
childitemlayout.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="@dimen/featured_text"
android:layout_height="@dimen/featured_image"
android:orientation="vertical"
android:background="#0000ff">
<Button android:id="@+id/btn"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:text="Button"
android:background="#ff00ff"/>
</LinearLayout>
dimen.xml
<?xml version="1.0" encoding="utf-8"?>
<resources>
<dimen name="featured_text">80dp</dimen>
<dimen name="featured_image">60dp</dimen>
</resources>