1

我对 Android 编程比较陌生。我已经阅读了很多关于这个主题的话题,但没有提到的解决方案对我有用。这是我正在尝试的。我正在尝试使用 XML 文件创建布局资源,并在我的 MainActivity 中执行 setContentView(R.layout.activity_main)。然后我有一个扩展 View 的自定义视图类,我尝试在其中修改 activity_main.xml 文件中定义的默认布局。但是,每当我尝试在单独的文件中实现的自定义视图中使用 findViewById(R.id.)(来自布局文件 activity_main.xml)获取视图 ID 时,我总是得到空值。如果我尝试使用 findViewById(...) 获取 MainActivity 类中的 id,我会得到一个正确的值。
我在这里做错了什么?

这是所有的代码片段

谢谢

这是文件“MainActivity.java”

public class MainActivity extends Activity {

@Override
public void onCreate(Bundle savedInstanceState) {


    super.onCreate(savedInstanceState);



    setContentView(R.layout.activity_main);

    MyView myView = new MyView(this, null);

      ....

这是文件 MyView.java

public class MyView extends View {

public static final String DEBUG_TAG = "MYVIEW" ;

public MyView(Context context, AttributeSet attrs) {
    super(context, attrs);


    View tablerow1 = (TableRow) findViewById (R.id.tableRow) ;

    Log.v(DEBUG_TAG," tablerow1 = " + tablerow1 + "\n");



}

这是文件activity_main.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/top_layout"  
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"  >
<TableLayout  
android:id="@+id/tableLayout1"  
android:layout_width="match_parent"  
android:layout_height="0dp"
android:layout_weight="2"
android:background="@color/red"
android:shrinkColumns="*"  
android:stretchColumns="*" >  
<TableRow
    android:id="@+id/tableRow1"  
    android:layout_height="wrap_content"  
    android:layout_width="match_parent"  
    android:gravity="center_horizontal">  

    <Button  
        android:id="@+id/button_00_1"  
        android:text="@string/button_1"
        android:textStyle="bold"
        android:background="@color/green"
        android:layout_margin="0.5dp"
        android:layout_width="0dp"
        android:layout_weight="0.5"           
        android:typeface="serif"></Button> 
    </TableRow>  
  </TableLayout>
</LinearLayout>

MyView.java 中的 findViewById(...) 调用总是返回 null,而如果我将它包含在 MainActivity.java 文件中,我会得到正确的非 null 值。

有人可以指出这里有什么问题吗?

谢谢

4

1 回答 1

4

您可以从活动的布局 xml 轻松访问任何视图/布局。您的代码中唯一缺少的是您尝试在 MyView 中执行 findViewById() 并尝试访问 Activity 的其他视图。此调用仅适用于包含在您的 MyView 中的视图,而不适用于该视图之外。您必须调用您尝试访问其视图的活动的 findViewByID()。例如:-

((Activity)context).findViewById(R.id.abc).setVisibility(View.VISIBLE);

在你的情况下,你可以这样做: -

public class MyView extends View {
   public static final String DEBUG_TAG = "MYVIEW" ;

   public MyView(Context context, AttributeSet attrs) {
   super(context, attrs);
   View tablerow1 = (TableRow) ((Activity)context).findViewById (R.id.tableRow) ;
   Log.v(DEBUG_TAG," tablerow1 = " + tablerow1 + "\n");
}
于 2012-11-06T07:51:17.327 回答