1

有很多这样的问题,但解决方案对我不起作用。

无论如何,我的主要活动有一个按钮,在它的 onclick 方法中,它会将我带到另一个活动,ViewPowerActivity。我有一个名为 power_view.xml 的布局 xml 文件。在里面我有一些布局:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="@dimen/screen_margin"
android:layout_marginRight="@dimen/screen_margin"
android:layout_marginTop="@dimen/screen_margin"
android:orientation="vertical" >
...

ViewPowerActivity 有基本的 onCreateMethod:

public class ViewPowerActivity extends Activity {
    private final static Powers powers=new StubPowers();

    @Override
public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.power_view);

        Power power=powers.getPowers().get(0);
        View powerView = findViewById(R.layout.power_view);
        ...
    }
    ...
}

上面的 findViewById 调用返回 null。

如果我在 setContentView(...) 之后删除所有代码并简单地返回那里,它会很好地显示空布局。我已经设置了内容视图,我已经清理了项目,我已经尝试将电源视图设置为主要活动,以及各种各样的事情。还能是什么?

4

2 回答 2

1

从您的代码中,很明显thar power_view是一个布局,即。xml。所以 R.id.power_view 是不正确的。

您似乎想访问该布局的父视图。然后执行以下操作。

您必须为父 LinearLayout 设置一个 id。

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
     android:id="@+id/parentLinear"
     android:layout_width="match_parent"
     android:layout_height="wrap_content"
     android:layout_marginLeft="@dimen/screen_margin"
     android:layout_marginRight="@dimen/screen_margin"
     android:layout_marginTop="@dimen/screen_margin"
     android:orientation="vertical" >
     ...

然后,

     View powerView = findViewById(R.id.parentLinear);

如果要在 powerView 中获取其他视图,则应在 xml 布局中将 id 设置为该视图,并通过findViewById(R.id.your_view)将该视图初始化为 power_view

于 2013-01-11T04:32:24.490 回答
0
     power_view.xml


    <?xml version="1.0" encoding="utf-8"?>
    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"

    android:id="@+id/layout"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_marginLeft="@dimen/screen_margin"
    android:layout_marginRight="@dimen/screen_margin"
    android:layout_marginTop="@dimen/screen_margin"
    android:orientation="vertical" >



    public class ViewPowerActivity extends Activity {
        private final static Powers powers=new StubPowers();

        @Override
    public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.power_view);

            Power power=powers.getPowers().get(0);
            View powerView = (ViewGroup)findViewById(R.id.layout);
            ...
        }
        ...
    }
于 2013-01-11T04:39:08.713 回答