Android : Android: Define programmatically RelativeLayout inside ViewFlipper

on Wednesday, August 6, 2014


Based on this article, I've tried to build a ViewFlipper with multiple RelativeLayouts.


When proceeding as written in article (only change the height), I got (as expected) a ViewFlipper normally displayed :


ViewFlipper with xml


My xml :



<ViewFlipper
android:id="@+id/view_flipper"
android:layout_width="fill_parent"
android:layout_height="200dp" >

<RelativeLayout
android:layout_width="fill_parent"
android:layout_height="fill_parent" >

<ImageView
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_gravity="center"
android:adjustViewBounds="true"
android:scaleType="centerCrop"
android:src="@drawable/img1" />

<TextView
style="@style/ImageTitle"
android:text="Test test" />
</RelativeLayout>
</ViewFlipper>


Style:



<style name="ImageTitle">
<item name="android:layout_width">fill_parent</item>
<item name="android:layout_height">50dp</item>
<item name="android:layout_alignParentBottom">true</item>
<item name="android:background">#99000000</item>
<item name="android:gravity">center</item>
<item name="android:maxLines">2</item>
<item name="android:textColor">#fff</item>
<item name="android:textStyle">bold</item>
<item name="android:textSize">18sp</item>
<item name="android:typeface">sans</item>
</style>


Then I've tried do generate RelativeLayout programmatically with the code below :



public void generateViewForFlipper(String url, int id, String text){

//new RelativeLayout
RelativeLayout relativeLayout = new RelativeLayout(this);

//Params for the RelaviteLayout
final ViewFlipper.LayoutParams frameLayoutLayoutParams = new ViewFlipper.LayoutParams(
ViewFlipper.LayoutParams.MATCH_PARENT,ViewFlipper.LayoutParams.MATCH_PARENT);

//ImageView
ImageView imageView = new ImageView (this);
imageView.setImageDrawable(getResources().getDrawable(R.drawable.img1));
imageView.setScaleType(ScaleType.CENTER_INSIDE);
imageView.setAdjustViewBounds(true);

// Params for the ImageView
final RelativeLayout.LayoutParams imageParams = new RelativeLayout.LayoutParams(
RelativeLayout.LayoutParams.MATCH_PARENT,RelativeLayout.LayoutParams.MATCH_PARENT );

//Application title
TextView textView = (TextView)getLayoutInflater().inflate(R.layout.tvtemplate, null);
textView.setText(text);


// Params for application title
final RelativeLayout.LayoutParams textParams = new RelativeLayout.LayoutParams(
LinearLayout.LayoutParams.MATCH_PARENT, 50);


mViewFlipper.addView(relativeLayout, frameLayoutLayoutParams);

relativeLayout.addView(imageView,imageParams);
relativeLayout.addView(textView);

}


tvtemplate.xml:



<?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
style="@style/ImageTitle" />


Result screen :


defined grammatically


As you can see, text is not aligned to the bottom, not "match_parent", and picture is not cropped..


Thank you


0 comments:

Post a Comment