How to load an XML inside a View in android?

后端 未结 2 1013
花落未央
花落未央 2021-01-13 08:42

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 follo

相关标签:
2条回答
  • 2021-01-13 09:10

    Suggestion: avoid naming your classes names very close to already existing classes (eg. View, Activity);

    Since you are extending View (which by default does not draw anything specific) you aren't able to see anything in your activity.

    Start by extending TextView object to get a feel.

    public class MyTextView extends TextView {
        public MyTextView(Context c){
        super(c);
    }
    

    // ----

    public class MyActivity extends Activity {
    
        MyTextView myTextView;
    
         @Override 
         protected void onCreate(Bundle savedInstance){
         super.onCreate(savedInstance);
         setContentView(myTextView = new MyTextView(this);
    
         myTextView.setText("It works!");
    }
    

    Hope this helps!

    0 讨论(0)
  • 2021-01-13 09:25

    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);
    
        }
    }
    
    0 讨论(0)
提交回复
热议问题