我已经在一个问题上苦苦挣扎了几天,到目前为止找不到我的问题的解决方案。我有两个类: - StartActivity 扩展 Activity - TimeGraphView 扩展 SurfaceView
我想要实现的是将 TimeGraphView 中的动态按钮添加到另一个视图(LinearLayout)。为此,我想使用 findViewById() 在 TimeGraphView 中获取 LinearLayout,但它返回 null,这应该是因为我在 TimeGraphView 中调用它,而不是在使用 setContentView() 的根元素中调用它;
所以我的问题是如何将按钮从自定义视图级别动态添加到另一个视图。
我的代码:
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>