开发者

Is it possible to initialize a View from different Layout?

I have an Activity and associated with it layout. Also I have another layout with some Views. I want to initialize a variable (TextView) from my Activity using a View from that standalone layout. I always get null.

public void onCreate(Bundle savedInstanceState) {
        super.onCreate(s开发者_开发百科avedInstanceState);
        setContentView(R.layout.main);
        button = (Button) findViewById(R.id.button); // This is OK 
// because R.id.button is from R.layout.main layout

        tvOne = (TextView) findViewById(R.id.first_item); // This is not OK
// because R.id.first_item is from another layout.
}


You can't instantiate a view within another layout, but you can instantiate a layout which can be the view you want.

LayoutInflater inflater = getLayoutInflater();
TextView text = (TextView) inflater.inflate(R.layout.contenttext, yourRootView, false);

Here would be the corresponding layout (contenttext.xml):

<?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
  android:layout_width="wrap_content"
  android:layout_height="wrap_content"
  android:textSize="12sp"/>


This is the correct behaviour, because findViewById() will only search for views set in the view hierarchy passed to setContentView()

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜