在自定义View类中扩展xml布局

Lum*_*oid 35 android view android-inflate

我有一个课程View1延伸View.我想R.layout.test2.xml在这堂课中充气View1.我在这个类中添加了以下代码

public class View1 extends View {

    View view;
    String[] countries = new String[] {"India", "USA", "Canada"};

    public View1( Context context) {
        super(context);
        LayoutInflater  mInflater=(LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        view=mInflater.inflate(R.layout.test2, null, false);
    }
}
Run Code Online (Sandbox Code Playgroud)

从另一个类Home我希望这个膨胀的视图在某些情况下存在,在Home类中我编写了以下代码:

public class Home extends Activity{

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.home);
        CreateView();   
    }

    public void CreateView() {
        LinearLayout lv=(LinearLayout)findViewById(R.id.linearlayout);
        View1 view = new View1(Home.this);
        lv.addView(view);
    }
}
Run Code Online (Sandbox Code Playgroud)

但是当我运行我的项目时,活动并没有向我显示任何内容.

Luk*_*rog 50

您不能将视图添加到View类中,而应该使用ViewGroup或其中一个子类(如Linearlayout,RelativeLayout等).然后你的代码将是这样的:

public class View1 extends LinearLayout {

    View view;
    String[] countries = new String[] {"India", "USA", "Canada"};

    public View1( Context context) {
        super(context);
        LayoutInflater  mInflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        mInflater.inflate(R.layout.test2, this, true);}}
Run Code Online (Sandbox Code Playgroud)

还行:

mInflater.inflate(R.layout.test2, null, false)
Run Code Online (Sandbox Code Playgroud)

不会向当前视图添加任何内容(因为false参数),它只是View从xml布局中膨胀.


Ara*_*cem 11

用这个

    LayoutInflater li = (LayoutInflater)getContext().getSystemService(infService);
    li.inflate(R.layout.test2, **this**, true);
Run Code Online (Sandbox Code Playgroud)

您必须使用this而不是null,并将false参数(布尔值AttachToRoot)更改为true

  • 为此,您需要从ViewGroup继承子类,而不是View (10认同)