我拥有的是一个几乎占据所有屏幕的画布,然后在它下面我想要一排按钮和其他一些小部件。所以我这样做了。
XML Code
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:id="@+id/myLayout"
android:orientation="vertical"
android:layout_height="match_parent" >
<com.zone.manager.Tab3
android:id="@+id/tab3_display"
android:layout_width="fill_parent"
android:layout_height="620dp" />
<LinearLayout
android:layout_width="match_parent"
android:orientation="horizontal"
android:layout_height="match_parent" >
<Button
android:id="@+id/addZone"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Add Zone" />
<Button
android:id="@+id/helpZone"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Help" />
<SeekBar
android:id="@+id/seekBar1"
android:paddingTop="9dp"
android:layout_width="179dp"
android:layout_height="wrap_content" />
</LinearLayout>
爪哇代码
public class Tab3 extends View implements OnTouchListener, OnClickListener {
public Tab3(Context context, AttributeSet attrs) {
View parent = (View) getParent();
addZone = (Button) parent.findViewById(R.id.addZone);
addZone.setOnClickListener(this);
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
. . . draws a bunch of stuff
}
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.addZone:
String w = "W~20~0~0~0~0~0";
Log.d("ZoneSize", "Zone set");
MyApplication.preferences.edit().putString( "ZoneSize", w ).commit();
MyApplication.preferences.edit().putBoolean("ZoneSizeReady", true).commit();
break;
}
}
但是,我的问题是我相信代码没有协调addZone的位置。因为当我激活addZone.setOnClickListener
时,我的程序会崩溃,但是当我没有激活它时,布局看起来像我想要的那样。我该怎么做才能解决这个问题?
addZone = (Button) findViewById(R.id.addZone);
addZone 将为空,因为com.zone.manager.Tab3
没有任何子项
所以很明显你的代码会崩溃
因此,要么您将为 com.zone.manager.Tab 子级提供这些子项,这些子项还需要将基类从 View 更改为 ViewGroup,
或者您从com.zone.manager.Tab parent开始。类似的东西
View parent = (View) getParent ();
addZone = (Button) parent.findViewById(R.id.addZone);
我有一些技巧可以让你避免这种奇怪的错误和其他错误:
自定义视图的代码依赖于使用自定义视图的 XML 布局。这是糟糕的编码。
相反,您应该使用 LayoutInflater,为其自定义视图使用布局 xml 文件,然后执行"findViewById"并将 clickListeners 添加到您想要的任何视图中。
我认为将自定义视图设置为保存其他视图的单击侦听器而不检查单击了哪些视图也是错误的。 要么添加一个检查,要么为每个视图添加一个不同的侦听器(我个人更喜欢)。