问题描述
我有一个扩展视图类。我有一个活动扩展另一个类,我想补充第一类活动类中被加载。
我尝试以下code
包Test2.pack;进口android.app.Activity;
进口android.content.Context;
进口android.os.Bundle;
进口android.view.View;公共类Test2的延伸活动{
/ **当第一次创建活动调用。 * / 静态视图V;
@覆盖
公共无效的onCreate(捆绑savedInstanceState){
super.onCreate(savedInstanceState);
的setContentView(R.layout.main); 尝试{
V =(视图)View.inflate(Test2.this,R.layout.main2,NULL);
}赶上(例外五){
的System.out.println(ERR+ e.getMessage()+ e.toString());
}
}
}类视图扩展视图{
公众的视野(上下文的背景下){
超级(上下文);
}
}
好吧想这一点,并意识到这是行不通的。问题是,该视图类没有添加子视图的方法。儿童意见应只能被添加到 ViewGroups
。布局,如的LinearLayout
,延长的ViewGroup
。因此,而不是延长查看,你需要扩展,例如的LinearLayout
。
然后,在你的XML,参考布局:
< my.package.MyView机器人:ID =@ + ID / CompId的android:layout_width =FILL_PARENT机器人:layout_height =FILL_PARENT/>
然后在您的自定义类,充气并添加:
公共类MyView的扩展的LinearLayout { 公共MyView的(上下文的背景下){
超级(上下文);
this.initComponent(上下文);
} 公共MyView的(上下文的背景下,ATTRS的AttributeSet){
超(背景下,ATTRS);
this.initComponent(上下文);
}
私人无效initComponent(上下文的背景下){ LayoutInflater吹气= LayoutInflater.from(背景);
视图V = inflater.inflate(R.layout.foobar,空,假);
this.addView(五); }}
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 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);
}
}
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);
}
}
这篇关于如何加载在android系统视图中的XML?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!