0

私が持っているのは、ほぼすべての画面を占めるキャンバスです。その下には、ボタンの行とその他のウィジェットが必要です。だから私はこれをしました。

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>

Java コード

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アクティブにしないと、レイアウトが希望どおりに見えるからです。これを修正するにはどうすればよいですか?

4

2 に答える 2

0
 addZone = (Button) findViewById(R.id.addZone);

子がないため、addZoneはnullになりますcom.zone.manager.Tab3

したがって、コードがクラッシュすることは明らかです

したがって、基本クラスをViewからViewGroupに変更する必要があるcom.zone.manager.Tabの子を指定します。

または、com.zone.manager.Tabの親から始めます。何かのようなもの

 View parent = (View) getParent ();
 addZone = (Button) parent.findViewById(R.id.addZone);
于 2012-06-10T15:58:29.553 に答える
0

このような奇妙なバグなどを回避するためのヒントがいくつかあります。

カスタム ビューのコードは、カスタム ビューを使用する xml レイアウトに依存しています。これは悪いコーディングです。

代わりに、 LayoutInflater を使用し、そのカスタム ビューにレイアウト xml ファイルを使用してから、「findViewById」を実行して、必要なビューに clickListeners を追加する必要があります。

どのビューがクリックされたかを確認せずに、他のビューのクリックリスナーを保持するようにカスタムビューを設定するのも間違っていると思います。チェックを追加するか、それぞれに異なるリスナーを追加します(個人的には好みです)。

于 2012-06-10T22:29:49.887 に答える