package com.test1;
import android.app.Activity;
import android.app.ExpandableListActivity;
import android.content.Context;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.BaseExpandableListAdapter;
import android.widget.TextView;
public class Test1Activity extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
c1 c1obj = new c1();
setContentView(c1obj.m1());
}
public class c1
{
public View m1()
{
LayoutInflater i = (LayoutInflater) Test1Activity.this.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View v = i.inflate(R.layout.main, null);
TextView tv = (TextView) v.findViewById(R.id.textView1);
tv.setText("Hello world !!!");
return v;
}
}
}
如果我尝试返回textview(tv)它会给我运行时错误,如果我返回视图(v)它工作正常可以有人告诉我为什么会这样。
答案 0 :(得分:1)
您发现运行时错误,因为Android Framework会抛出IllegalStateException,因为您尝试将TextView视图添加到活动的视图层次结构中。换句话说,您正在尝试为已具有父级(某种布局)的视图(TextView)设置新的父级。 Android Framework不允许自动更改父级,并且会抛出异常。
尝试添加以下行 - 似乎这会对您有所帮助:
ViewGroup vg = (ViewGroup)tv.getParent();
vg.removeView(tv);