这是我第一次创建Android应用程序,但我不确定如何解决此问题。我试图通过ID将ImageButton变量指向现有的ImageButton
,但我仍然收到NullPointerException
。下面的代码:ImageButton在赋值后为'null'
...
import android.widget.ImageButton;
public class StartActivity extends ActionBarActivity {
ImageButton addButton;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_start);
addButton = (ImageButton) findViewById(R.id.add_category_button);
}...
的ImageButton
位于布局card_categories
。下面是该布局的XML:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@color/main_page"
android:weightSum="1">
<ImageButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/add_category_button"
android:layout_gravity="right"
android:background="@drawable/add_button"
android:width="50dp"
android:height="50dp"
/>
</LinearLayout>
我不知道这个问题是不正确的id
,或者是什么,但它不是正确抽取在XML中ImageButton
。谢谢你的帮助!
更新:我试图在setContentView(R.layout.card_categories)
之后分配ImageButton
,但它仍然为空。
OnClickListener myCardsHandler = new OnClickListener() {
public void onClick(View v) {
setContentView(R.layout.card_categories);
addButton = (ImageButton) findViewById(R.id.add_category_button);
loadCategories(dbHandler, categories);
}
};
_“的ImageButton的位于布局card_categories” _但你夸大'R.layout.activity_start'因此,如何将你希望得到你的'ImageButton'? – 2015-02-17 23:15:45
确保:'activity_start.xml'包含'ImageButton'。我认为你可以'setContentView'为不同的布局。 – 2015-02-17 23:18:07
你在OnClickListener好友中指定它:)这应该在Activity#OnCreate生命周期方法中理想地发生! – 2015-02-17 23:41:03