如何在Android中的视图上添加自定义视图?

时间:2011-09-02 00:01:03

标签: android layout view

我在Android中有一个图表视图(自定义视图)和一个主视图。根据用户的偏好,我想在主视图中添加1-5个图形视图,但我不太清楚如何操作。 (我使用纯Java而不是xml)。我正在阅读我可能不得不使用相对布局或其他东西来堆叠视图。

欢迎任何建议或建议

2 个答案:

答案 0 :(得分:3)

在你的活动中,你可能会在onCreate()方法的开头有这样的东西:

setContentView(R.layout.main);

在main.xml文件中你可能有一个元素是某种布局。我现在假设LinearLayout,但它适用于所有类型。您需要获得对此布局的引用,并且为此必须具有id。因此,如果该布局中没有类似的内容,则需要添加它:

android:id="@+id/myMainLayout"

然后在你调用setContentView()之后的某个时候,你可以找到对你的布局的引用,如下所示:

LinearLayout myLayout = (LinearLayout)findViewById(R.id.myMainLayout);

获得对布局的引用后,您可以使用以下内容添加图表视图:

myLayout.addView(graph1);
myLayout.addView(graph2);
//etc...

如果您想要一起跳过xml布局,则可以在java中进行布局。要做到这一点,它会这样:

LinearLayout myLayout = new LinearLayout(YourActivity.this);
myLayout.addView(graph1);
myLayout.addView(graph2);
setContentView(myLayout);

请注意,您只能调用一次setContentView(),因此如果要添加多个View,则需要将某种布局传递给它。

编辑:

我从未特别尝试过,但我认为你可以从自定义视图中的构造函数调用addView():

public CustomView() {
    this.addView(anotherView);
}

您的布局也有自定义视图吗?

答案 1 :(得分:1)

以下是图表的自定义视图示例。需要在布局中的某处具有LinearLayout,其ID设置为@ + id / ll和图形的大小:

public class RootActivity extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    int[] graphData = {3,5,2,7,4,8,1,5,9};

    LinearLayout ll = (LinearLayout) findViewById(R.id.ll);  
    GraphView graphView = new GraphView(this);
    ll.addView(graphView);


    //call this method with every new set of data
    graphView.drawGraph(graphData);


}


class GraphView extends View{
 int[] graphData;
 Paint graphPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
 int screenH;
 int screenW;
 int colW;
 int colH;
 int columnCount;

 public GraphView(Context context) {
    super(context);

    graphPaint.setColor(Color.MAGENTA);
    graphPaint.setStyle(Style.FILL);
}


 @Override     
 public void onSizeChanged (int w, int h, int oldw, int oldh) {         
     super.onSizeChanged(w, h, oldw, oldh);         
     screenW = w;         
     screenH = h; 
 }


public void drawGraph(int[] graphData){
    this.graphData = graphData;
    columnCount = graphData.length;
    invalidate();
}


@Override     
public void onDraw(Canvas canvas) {         
    super.onDraw(canvas); 

    colW = (screenW - 10) / columnCount;
    int graphStep = 20;
    int columnSpace = 5;

    canvas.drawText("GRAPH", 10, 10,  graphPaint);

    for (int i= 0 ; i < columnCount; i++){
        //draw columns from bottom up
        canvas.drawRect(
                new Rect(
                i * colW + 5, 
                screenH - 5 - (graphData[i] * graphStep), 
                i * colW + 5 + colW - columnSpace, 
                screenH - 5     
                ), 
                graphPaint);
    }



}