我已经在几天内遇到问题,到目前为止无法找到问题的解决方案。 我有两节课: - StartActivity扩展了Activity - TimeGraphView扩展了SurfaceView
我想要实现的是将TimeGraphView中的动态按钮添加到另一个视图(LinearLayout)。 这样做是想用FindViewById()在TimeGraphView中获取LinearLayout但是它返回null,它应该因为我在TimeGraphView中调用它而不是在root元素中我使用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>
答案 0 :(得分:0)
你不能以这种方式使用它。如果你添加一个根元素Linearlayout并引用它,那么它可能会起作用。如果你想获得TimeGraphLayout类:
TimeGraphView layout = (TimeGraphView) findViewById(R.id.TimeGraphLayout);
setContentView(layout);
您执行此操作的原始方式无效,因为TimeGraphView不是LinearLayout