我有一个扩展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);
}
}
从另一个类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);
}
}
但是当我运行我的项目时,活动并没有向我显示任何内容。
答案 0 :(得分: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);}}
还行:
mInflater.inflate(R.layout.test2, null, false)
不会向当前视图添加任何内容(因为false
参数),它只是从xml布局中膨胀View
。
答案 1 :(得分:11)
使用此
LayoutInflater li = (LayoutInflater)getContext().getSystemService(infService);
li.inflate(R.layout.test2, **this**, true);
您必须使用this
,而不是null,并将false
参数(布尔值AttachToRoot)更改为true
答案 2 :(得分:3)
使用下面的代码来扩充您的布局,然后您可以将该视图用于任何目的。这将为您提供XML文件的最父级布局。键入cast并相应地使用它。
View headerView = View.inflate(this, R.layout.layout_name, null);
答案 3 :(得分:1)
您正在添加家庭活动空白视图。因为在View1类中,您只能扩充视图但不能在任何地方添加。
答案 4 :(得分:0)
在科特林
LayoutInflater.from(this).inflate(R.layout.custom_toolbar, null, false)