Reputation:
As you can see in the above image, the class view is declared inside the MainActivity so it doesnot have an XML file. I want to add a button on the that custom view and manipulate it.
How can i display a custom view in xml if the class View is inside the java class that does not extends view?
Upvotes: 1
Views: 998
Reputation: 1543
I don't think you can set any other view inside a view. check description, I think only ViewGroup and layouts like LinearLayout
, RelativeLayout
which extends ViewGroup
can only add other views using addView(View view)
,
example as follows
You can create your an xml layout file and put your custom view in it.
example xml file containing your custom view
<?xml version="1.0" encoding="utf-8"?>
<com.example.package.MyView
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
java code And then inflate it in a view.
// Inflate your xml view using layout inflater.
LayoutInflater inflater = getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View myView = (MyView) inflater.inflate(R.layout.example, null);
// now create a container class or map any of it from main_activity.xml layout.
LinearLayout linear = new LinearLayout(this);
/* LinearLayout linear = (LinearLayout) findViewById(R.layout.myLayout); */
// if you have created it programatically, set its width and height as following
linear.setLayoutParams(new ViewGroup.LayoutParams(
ViewGroup.LayoutParams.MATCH_PARENT, // width
ViewGroup.LayoutParams.MATCH_PARENT)); // height
// else mention it in layout xml file.
linear.removeAllViews(); // clear layout before setting new one.
linear.addView(myView); // set custom view inside layout.
Now you can assign manipulate your myView anyhow. if you still want to add button. Create button in xml file and inflate or create programatically and add it to linear.addView(View view);
Upvotes: 1
Reputation: 1213
Create a custom layout in XML, assign it a view. Then you can add the view to your other layouts. Look at this tutorial for details on creating custom views
Upvotes: 0