How to load XML inside a view in Android?

I have a class that extends the view. I have another class that extends the activity, and I want to add the first class to load 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);     
    }   
}
+5
source share
2 answers

I tried it well, and realized that it did not work. The problem is that there are no methods in the View class to add child views. Child views should only be added to ViewGroups. Layouts, such as LinearLayoutexpand ViewGroup. Therefore, instead of expanding the View you need to extend, for example LinearLayout.

Then in your XML, link to the layout using:

<my.package.MyView
    android:id="@+id/CompId"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"/>

:

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);

    }
}
+18

: (, View, Activity);

( ), .

TextView, .

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!");
}

, !

0

All Articles