I have a custom view in my app that I draw using the onDraw()
function in the View. Also it needs some data from the ACtivity to draw the graphic. So instead of using the standard setContentView(R.layout.myview)
I am using the following -
MyView mv = new MyView(this, userData);
setContentView(mv);
This seemed to work until I added a textview
above the customview. Then I realized that the above code does not show the textview at all. Also the onFinishInflate()
i开发者_如何学Gos never called. Do I have to inflate the layout myself in this case? If so do I have to call the onDraw()
function myself too?
Thanks, - P
onFinishInflate ()
Finalize inflating a view from XML. This is called as the last phase of inflation, after all child views have been added.
When you create your view by code (new ...
) you are not inflating it... on the other hand, if you declare it in the XML or you use something like getLayoutInflater().inflate(R.layout.your_view,null,null);
then you are inflating it (and onFinishInflate
) will be called.
It does not matter how you are doing it, onDraw
method will always be called; so you don't have to invoke it manually.
By the way... it's always a good idea to keep your custom view on the XML, even if it needs data. So you have at least two options:
setContentView(R.layout.your_layout);
YourCustom custom = (YourCustom)findViewById(R.id.custom);
custom.setUserData(userData);
or... you can fetch that data from the custom view (not recommended):
// inside your custom view...
UserData userData = Someclass.getUserData(getContext());
// etc... so that you don't have to pass it from the activity
What you should have here is a layout that contains the TextView
and your MyView
and then inside your activity, find your custom view and pass in your user data. Your MyView
can then use this during its onDraw()
. Perhaps something like this:
res/layout/main.xml
:
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="veritcal">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Hello World" />
<my.package.MyView
android:id="@+id/myview"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
</LinearLayout>
src/my/package/MyView.java
:
public class MyView extends View {
UserData mUserData = null;
public void setUserData(userData) {
mUserData = userData;
}
@Override
protected void onDraw(Canvas canvas) {
performCustomDrawingWithUserData(mUserData);
super.onDraw(canvas);
}
}
src/my/package/MyActivity.java
:
public class MyActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
// pass the user data into myview here.
MyView myView = (MyView) findViewById(R.id.myview);
myView.setUserData(userData);
}
}
精彩评论