I am having a class that extends View. I have another class that extends activity and I want to add the first class to be loaded inside the activity class. I tried the following code
package Test2.pack;
import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.view.View;
public class Test2 extends Activity {
/** Called when the activity is first created. */
static view v;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
try{
v = (view) View.inflate(Test2.this, R.layout.main2, null);
}catch(Exception e){
System.out.println(" ERR " + e.getMessage()+e.toString());
}
}
}
class view extends View{
public view(Context context) {
super(context);
}
}
A View occupies a rectangular area on the screen and is responsible for drawing and event handling. Views are used for Drawing Shapes like Circles,Rectangles,Ovals etc . Just Use View with background and apply a Shape using Custom Drawable.
To efficiently reuse complete layouts, you can use the <include/> and <merge/> tags to embed another layout inside the current layout. Reusing layouts is particularly powerful as it allows you to create reusable complex layouts. For example, a yes/no button panel, or custom progress bar with description text.
Go to the app > res > layout > right-click > New > Layout Resource File and name the file as custom_layout. Below is the code for the custom_layout. xml and the file should be present with merge contents.
Ok tried this, and realized that it doesn't work. The problem is, that the View class does not have methods for adding child views. Child views should only be added to ViewGroups
. Layouts, such as LinearLayout
, extend ViewGroup
. So instead of extending View, you need to extend for example LinearLayout
.
Then, in your XML, reference to the layout with:
<my.package.MyView
android:id="@+id/CompId"
android:layout_width="fill_parent"
android:layout_height="fill_parent"/>
Then in your custom class, inflate and add:
public class MyView extends LinearLayout {
public MyView(Context context) {
super(context);
this.initComponent(context);
}
public MyView(Context context, AttributeSet attrs) {
super(context, attrs);
this.initComponent(context);
}
private void initComponent(Context context) {
LayoutInflater inflater = LayoutInflater.from(context);
View v = inflater.inflate(R.layout.foobar, null, false);
this.addView(v);
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With