如何在android中的View中加载XML?

Jam*_*mes 5 android

我有一个扩展View的类.我有另一个扩展活动的类,我想添加要在活动类中加载的第一个类.我尝试了以下代码

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);     
    }   
}
Run Code Online (Sandbox Code Playgroud)

Tuo*_*asR 18

好试过这个,并意识到它不起作用.问题是,View类没有添加子视图的方法.只应添加子视图ViewGroups.布局,例如LinearLayout,扩展ViewGroup.因此,您需要扩展,而不是扩展View LinearLayout.

然后,在您的XML中,引用布局:

<my.package.MyView
    android:id="@+id/CompId"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"/>
Run Code Online (Sandbox Code Playgroud)

然后在您的自定义类中,膨胀并添加:

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

    }
}
Run Code Online (Sandbox Code Playgroud)

  • 您可以编辑自己的答案来改进它们.将此作为评论添加意味着阅读此答案的每个人都可能会错过它. (4认同)