【问题标题】:The LinearLayout returned is null in the subclass of PreferenceActivity返回的 LinearLayout 在 PreferenceActivity 的子类中为 null
【发布时间】:2012-07-06 11:09:38
【问题描述】:

我的库项目中有一个 SettingsActivity,它是 PreferenceActivity 的子类

oncreate 方法如下所示

addPreferencesFromResource(R.xml.preferences);
setContentView(R.layout.main);

preference.xml 文件的结构类似于元素 PreferenceScreen -> PreferenceCategory -> Preference 我的main main.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">


  <!--Listview will be replaced by preferences  -->

  <ListView android:id="@android:id/list"
          android:layout_width="fill_parent"
          android:layout_height="fill_parent" />

</LinearLayout>

上面的类SettingsActivity在另一个项目中被子类化,看起来像这样

public class SettingsActivityFree extends SettingsActivity 
{
       private AdView adView;

       @Override
   protected void onCreate(Bundle savedInstanceState) 
       {        
    super.onCreate(savedInstanceState);

            //...

            // layout returned will be null ..
            LinearLayout layout = (LinearLayout)findViewById(R.layout.main);

            // Add the adView to it
            layout.addView(adView);
       }

问题是我试图从父类中获取 LinearLayout 以便我可以在其中添加我的东西,但由于某种原因它返回 null ,我在 SettingsActivity 类中有 LinearLyout 的原因是因为我想放一些广告等在首选项的顶部,而无需将广告特定代码放入库项目中

如果我在这里遗漏了什么,请告知,

谢谢

【问题讨论】:

    标签: android


    【解决方案1】:

    首先,您需要使用android:id="@+id/whatever" 为您的LinearLayout 提供id。然后你可以使用findViewById(R.id.whatever)搜索它。

    【讨论】:

      【解决方案2】:

      您确实应该检查开发人员网站。你没有正确地做到这一点。查看有关 ListView 和 ListActivity 的文档。在使用之前了解它的工作原理。

      也作为提示:

      你不要这样做(LinearLayout)findViewById(R.layout.main);

      检索视图时,您会在R.id.(whatever) 中找到它,而不是在R.layout.(whatever)

      【讨论】:

        猜你喜欢
        • 2023-04-04
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2023-03-10
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多