我有一个这样的布局,main_layout:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent">
<RelativeLayout
android:id="@+id/testLayout"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="64dp"
>
<ImageButton
android:layout_width="32dp"
android:layout_height="32dp"
android:layout_alignParentLeft="true"
android:layout_marginLeft="50dp"/>
<ImageButton
android:layout_width="32dp"
android:layout_height="32dp"
android:layout_alignParentLeft="true"
android:layout_marginLeft="100dp"
android:visibility="invisible"/>
</RelativeLayout>
</RelativeLayout>
现在,我想访问Java代码中的第二个按钮,所以这是导致NullPointerException的代码部分:
RelativeLayout rl = (RelativeLayout) findViewById(R.id.testLayout);
ImageButton b = (ImageButton) rl.getChildAt(1);
我发现了一个新的有趣点。此代码显示rl在代码段中只有一个孩子,所以rl根本没有第二个按钮。为什么?
log.d("child Counter", String.valueOf(rl.getChildCount()));
这在LogCat中显示1
对于那些认为这是问题原因的人,这是onCreate方法,但我知道并非如此。
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_layout);
}
您的代码运行正常,请尝试这种方式,希望这将帮助您解决问题。
activity_main.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/testLayout"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="64dp">
<ImageButton
android:layout_width="32dp"
android:layout_height="32dp"
android:layout_alignParentLeft="true"
android:layout_marginLeft="50dp"/>
<ImageButton
android:layout_width="32dp"
android:layout_height="32dp"
android:layout_alignParentLeft="true"
android:layout_marginLeft="100dp"
android:visibility="invisible"/>
</RelativeLayout>
MainActivity.java
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
RelativeLayout rl = (RelativeLayout) findViewById(R.id.testLayout);
ImageButton b1 = (ImageButton) rl.getChildAt(0);
b1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Toast.makeText(MainActivity.this,"Image Button 1 clicked",Toast.LENGTH_SHORT).show();
}
});
ImageButton b2 = (ImageButton) rl.getChildAt(1);
b2.setVisibility(View.VISIBLE);
b2.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Toast.makeText(MainActivity.this,"Image Button 2 clicked",Toast.LENGTH_SHORT).show();
}
});
}
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句