我如何获取对<include>
元素的引用(我能否通过id获取添加到布局中的<include>
标记中的元素的引用)?
我如何获取对<include>
元素的引用(我能否通过id获取添加到布局中的<include>
标记中的元素的引用)?
使用findViewById
获取引用
请参考以下示例
RelativeLayoutTesting.java
import android.app.Activity;
import android.os.Bundle;
import android.widget.EditText;
public class RelativeLayoutTesting extends Activity {
android.widget.RelativeLayout currentView = null;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate( savedInstanceState );
// set the relative layout as our view
setContentView(R.layout.main1);
EditText et = (EditText) findViewById(R.id.myEditText);
et.setText("My Edit");
}
}
main1.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical"
android:background="#ffffff">
<ImageButton
android:id="@+id/alpha"
android:layout_width="fill_parent"
android:layout_height="50dip"
android:background="#ff0000" />
<include
layout="@layout/edittext_layoout"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</LinearLayout>
edittext_layout.xml
<?xml version="1.0" encoding="utf-8"?>
<EditText xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/myEditText"
android:layout_width="wrap_content"
android:layout_height="wrap_content" >
</EditText>
你只需要像往常一样:
TextView textView = (TextView) findViewById( R.id.textViewFromIncludedLayout );
请确保您没有相同的ID - 例如,在主布局中有一个myTextView
,然后您在主布局中包含一个布局,该布局也具有myTextView
。
您可以使用以下方式获取引用
findViewById
findViewById
将尝试在当前显示在屏幕上的内容中查找给定 ID 的引用(即使已隐藏或消失,重要的是它必须以某种方式被填充)。