开发者

android view and textview confusion in inflating and returning

package com.test1;

import android.app.Activity;
import andro开发者_JAVA技巧id.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;
        }
    }
}

if i try to return textview(tv) it gives me runtime error if i return view(v) it works fine can anyone tell me why is that.


You observe a runtime error because Android Framework throws an IllegalStateException since you try to add a TextView view into your activity's views hierarchy. In other words you're trying to set new parent for the view (TextView) which already has a parent (some kind of layout). Android Framework doesn't allow to change the parent automatically and it throws an exception.

Try to add following lines - seems this will help you:

        ViewGroup vg = (ViewGroup)tv.getParent();
        vg.removeView(tv);
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜