摘要活动导致findViewById()无法工作。

3

我有一个抽象的Activity,因为我的大多数活动都共享相同的菜单:

public abstract class ActivityBase extends Activity {

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.menubar, menu);

        return true;
    }

    @Override
    public boolean onPrepareOptionsMenu(Menu menu) {
      //...

      return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
      //...
    }
}

现在,当我使用那个类(继承它)时,findViewById()方法不再起作用。无论我是否在特定类中继承它,一旦它出现在继承树中的任何位置,它都不再起作用。例如:
public class SomeOther extends ActivityBase {
}

public class Home extends Activity {

  @Override
  public void onCreate (Bundle savedInstance) {
    super.onCreate(savedInstance);
    setContentView(R.layout.main);

    Button b = (Button)findViewById(R.id.button); // fails, NullPointerException
}

什么可能导致这种情况,更重要的是,我该如何解决?

它是怎么失败的?按钮为空还是什么?ClassCastException吗?请粘贴logcat。 - Ovidiu Latcu
按钮是否在同一个main.xml文件中? - user370305
是的。在我引入“ActivityBase”类之前,它是可以工作的。 - Femaref
3个回答

1
在我的情况下,这个工作完美(试试这个)...
public abstract class ActivityBase extends Activity {

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    return true;
}

@Override
public boolean onPrepareOptionsMenu(Menu menu) {
  //..
  return true;
 }
}

并且

public class MyActActivity extends ActivityBase {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    Log.e("HI", "Hello");
    TextView tv=(TextView)findViewById(R.id.Settings_phoneNumbersT1);
    Log.e("HI", tv.toString());
}
}

以及main.xml

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

   <TextView
        android:id="@+id/Settings_phoneNumbersT1"
        android:textSize="14sp"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textColor="#ffffff" android:text="Hellofffff"/>


 </LinearLayout>

所以,我不认为这是抽象ActivityBase类的问题。


抱歉,我忘记在示例中调用了 setContentView(...) - Femaref
没错,现在对我也起作用了。原因在别处,只是在那里表现出来了。 - Femaref
我只能在两天后接受自己的答案。虽然我感谢你的帮助,但那并不是真正的解决方案。还是给你点赞以示感谢。 - Femaref

0

试试这个……

Button b = (Button)Home.this.findViewById(R.id.button);

这是为了确保调用当前类的findviewById而不是超类的。


0

NullPointerException 是由其他地方引起的,只是在该方法中表现出来。如果您从 Application 派生并尝试调用 getSharedPreferences,它会失败,但您无法确定具体原因。


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