如何在活动中创建的布局中添加背景图像

时间:2012-08-29 16:20:48

标签: java android image background

我在java代码中创建了一个LinearLayout,但我不知道如何添加图像背景。

这是我对LinearLayout的代码:

LinearLayout layout = new LinearLayout(this);
        layout.setOrientation(1);

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    /** Create a new layout to display the view */
    LinearLayout layout = new LinearLayout(this);
    layout.setOrientation(1); 

    TextView variacion[];

     try {

        /** Handling XML */
        SAXParserFactory spf = SAXParserFactory.newInstance();
        SAXParser sp = spf.newSAXParser();
        XMLReader xr = sp.getXMLReader();

        /** Send URL to parse XML Tags */
        URL sourceUrl = new URL("http://www.bovalpo.com/cgi-local/xml_bcv.pl?URL=75");

        /** Create handler to handle XML Tags ( extends DefaultHandler ) */
        MyXMLHandler myXMLHandler = new MyXMLHandler();
        xr.setContentHandler(myXMLHandler);
        xr.parse(new InputSource(sourceUrl.openStream()));

        } catch (Exception e) {
            System.out.println("XML Pasing Excpetion = " + e);
        }

    /** Get result from MyXMLHandler SitlesList Object */
    sitesList = MyXMLHandler.sitesList;

    /** Assign textview array lenght by arraylist size */
    registro = new TextView[sitesList.getRegistro().size()];
//    nemotecnico = new TextView[sitesList.getNemotecnico().size()];
    variacion = new TextView[sitesList.getVariacion().size()];

   //category = new TextView[sitesList.getName().size()];

    /** Set the result text in textview and add it to layout */
    for (int i = 0; i < sitesList.getRegistro().size(); i++) {

        variacion[i] = new TextView(this);
        variacion[i].setText(sitesList.getVariacion().get(i));



        Pattern pattern = Pattern.compile("^\\+?[0-9]+([,\\.][0-9]*)?$");
        Matcher matcher = pattern.matcher(sitesList.getVariacion().get(i));
        if (!matcher.matches())

        variacion[i].setTextColor(Color.parseColor("#ff0000"));
        else
        variacion[i].setTextColor(Color.parseColor("#008000")); 


       layout.addView(variacion[i]);
    }   
    /** Set the layout view to display */
   setContentView(layout);

}
}

1 个答案:

答案 0 :(得分:0)

使用:

 LinearLayout layout = new LinearLayout(this);
 layout.setOrientation(1);
 layout.setBackgroundResource(R.drawable.background);

backgroundres文件夹中的背景图片。