1

私はすでに数日間問題に苦しんでおり、これまでのところ問題の解決策を見つけることができませんでした. 2 つのクラスがあります: - StartActivity は Activity を拡張します - TimeGraphView は SurfaceView を拡張します

私が達成したいのは、TimeGraphView 内から別のビュー (LinearLayout) に動的にボタンを追加することです。そのためには、findViewById() を使用して TimeGraphView 内でその LinearLayout を取得したかったのですが、null を返します。

私の質問は、カスタム ビュー レベルから別のビューにボタンを動的に追加する方法です。

そして私のコード:

public class StartActivity extends Activity {

    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.time_graph);

        LinearLayout layout = (LinearLayout) this.findViewById(R.id.TimeGraphLayout);
        //here I can add button but it's not what I want
    }
}

と ...

public class TimeGraphView extends SurfaceView implements SurfaceHolder.Callback, Runnable {

    public TimeGraphView(Context context) {
        super(context);
    }

    public TimeGraphView(Context context, AttributeSet set) {
        super(context, set);
    }

    public TimeGraphView(Context context, AttributeSet set, int arg) {
        super(context, set, arg);
    }

    public void run() {
        while (run) {
            if (something) {
                LinearLayout layout = (LinearLayout) findViewById(R.id.TimeGraphLayout);
                if (layout != null) {
                    Button button = new Button(context);
                    button.setText(text);
                    layout.addView(button);
                } else {
                    Log.e("TimeGraphView", "TimeGraphLayout is null");
                    //and "layout" is always null and that's the problem ;(
                }
            }
        }
    }
}

...そして私のXML

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

    <HorizontalScrollViewa
        android:id="@+id/TimeGraphPanel"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" >

        <LinearLayout
            android:id="@+id/TimeGraphLayout"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:orientation="horizontal" />
    </HorizontalScrollView>

    <my.package.TimeGraphView
        android:id="@+id/TimeGraphChart"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />

</LinearLayout>
4

1 に答える 1

1

そんな使い方はできません。ルート要素 Linearlayout を追加して参照すると、さらに機能する可能性があります。TimeGraphLayout クラスを取得したい場合:

 TimeGraphView layout = (TimeGraphView) findViewById(R.id.TimeGraphLayout);
 setContentView(layout);

TimeGraphView は LinearLayout ではないため、元の方法は機能しません。

于 2016-07-04T10:29:52.590 に答える