如何在代码中获取 <include> 元素的引用?

3

我如何获取对<include>元素的引用(我能否通过id获取添加到布局中的<include>标记中的元素的引用)?


1
你可能需要详细说明或举例说明如何通过<include>标签添加。您可以使用findViewById(R.id.yourViewId)查找对您的XML视图的引用。 - FoamyGuy
3个回答

1

使用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>

0

你只需要像往常一样:

TextView textView = (TextView) findViewById( R.id.textViewFromIncludedLayout );

请确保您没有相同的ID - 例如,在主布局中有一个myTextView,然后您在主布局中包含一个布局,该布局也具有myTextView


0

您可以使用以下方式获取引用

findViewById

无论您使用何种方式将视图添加到活动中,都不重要:findViewById 将尝试在当前显示在屏幕上的内容中查找给定 ID 的引用(即使已隐藏或消失,重要的是它必须以某种方式被填充)。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接