ImageView主要是用来显示图片的控件,可以对图片进行放大、缩小和旋转的功能。
android:scaleType属性指定ImageView控件显示图片的方式,
例如:center表示图像以不缩放的方式显示在ImageView控件的中心,如果设置为fitCenter,表示图像按照比例缩放至合适的位置,并在ImageView控件的中心。
任务:学习ImageView控件的基本用法
app展示:
主要java代码:
public static class PlaceholderFragment extends Fragment {
public PlaceholderFragment() {
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main, container, false);
ImageView imageView = (ImageView)rootView.findViewById(R.id.imageview);
//设置第一个图片的比例大小
//表示宽度200,高度100
imageView.setLayoutParams(new LinearLayout.LayoutParams(200,100));//设置整个布局的参数
getActivity().setTitle("height:"+imageView.getLayoutParams().height+"--width-->>"+imageView.getLayoutParams().width);
return rootView;
}
}
XML:
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="scaleType:center 為縮放,放在ImageView里" ></TextView>
<!-- 設置图片来源 -->
<!--设置缩放显示的方式 -->
<ImageView
android:id="@+id/imageview"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#F00"
android:src="@drawable/background"
android:scaleType="center"
></ImageView>
<TextView
android:layout_width="fill_parent"
android:layout_marginTop="20dp"
android:layout_height="wrap_content"
android:text="scaleType:fitCenter 按照比例进行缩放" ></TextView>>
<!-- 設置图片来源 -->
<!-- 图像按照比例缩放至合适的位置,并放在Imageview控件的中心 -->
<ImageView
android:id="@+id/imageview2"
android:layout_width="300dp"
android:layout_height="200dp"
android:background="#FFF"
android:src="@drawable/background"
android:scaleType="fitCenter"
android:padding="10dp"
></ImageView>
总结:
1.XML中出现了 Error parsing XML: not well-formed (invalid token)错误。
解决办法:格式的问题,看上去没有问题,把那个textview重写一下,确认没有中文或全角字符,再clean一下
2.XML中的备注不能写在控件里面。
3. 图像按照比例缩放至合适的位置,并放在Imageview控件的中心 android:scaleType="fitCenter"
4.java中报错:Cannot make a static reference to the non-static method setTitle(CharSequence) from the type Activity
报错语句:setTitle("height:"+imageView.getLayoutParams().height+"--width-->>"+imageView.getLayoutParams().width);
报错原因:setTitle是Activity中设置标题的一个方法。在fragment中没有setTitle方法,在fragment必须通过getActivity()找到该fragment所属的activity来调用setTitle这个方法。
解决办法:getActivity().setTitle("height:"+imageView.getLayoutParams().height+"--width-->>"+imageView.getLayoutParams().width);