Android : Proper way override fixed size custom view

on Sunday, October 5, 2014


I have a custom view with Yellow background. I plan to add a Red background TextView, with match_parent for both width and height on it. Here's what I had done.


MainActivity.java



public class MainActivity extends Activity {

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

LinearLayout mainView = (LinearLayout)this.findViewById(R.id.screen_main);
RateAppBanner rateAppBanner = new RateAppBanner(this);
mainView.addView(rateAppBanner);
}
}


RateAppBanner.java



public class RateAppBanner extends LinearLayout {

public RateAppBanner(Context context) {
super(context);

setOrientation(HORIZONTAL);

LayoutInflater.from(context).inflate(R.layout.rate_app_banner, this, true);

this.setBackgroundColor(Color.YELLOW);
}
}


rate_app_banner.xml



<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal">

<TextView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:textColor="#ffffffff"
android:background="#ffff0000"
android:text="Hello World" />

</LinearLayout>


enter image description here


Now, I would like to have a fixed width & height custom view. I realize, after I'm having fixed width & height custom view, the added TextView doesn't obey match_parent attribute.


Here's the change I had done on custom view.


RateAppBanner.java



public class RateAppBanner extends LinearLayout {
...

@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
int desiredWidth = 320;
int desiredHeight = 50;

desiredWidth = (int)TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, desiredWidth, getResources().getDisplayMetrics());
desiredHeight = (int)TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, desiredHeight, getResources().getDisplayMetrics());

super.onMeasure(desiredWidth, desiredHeight);
//MUST CALL THIS
setMeasuredDimension(desiredWidth, desiredHeight);
}


I realize the added TextView doesn't match_parent anymore!


enter image description here


Now, we can see the Yellow custom view is having fixed size 320x50. I expect the Red TextView will fill up the entire custom view due to match_parent attribute.


However, that's not the case. I believe my implementation for custom view's onMeasure isn't correct. May I know what is the correct way to fix this?


The complete source code can be downloaded from abc.zip


0 comments:

Post a Comment