mardi 13 mai 2014

Converting XML android:background to Java Program Code


Vote count:

2




I have created a RelativeLayout in an XML that contains a TextView like this:



<TextView
android:id="@+id/textView5"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="@+id/textView3"
android:layout_below="@+id/button1"
android:layout_marginTop="28dp"
android:background="@drawable/rounded_edges"
android:textSize="25sp" />


so that a circle will be drawn under the text. The rounded_edges.xml is defined as follows:



<?xml version="1.0" encoding="UTF-8"?>
<shape xmlns:android="http://ift.tt/nIICcg"
android:shape="oval">
<corners android:radius="10dip"/>
<stroke android:color="#c00000" android:width="2dip"/>
<solid android:color="#ffffff"/>
</shape>


Then I needed more textViews depending on a number entered by user. Each textView will show a number with a circle below. I succeeded in creating the textViews programmatically in the Java code as below, except for the circle:



final TextView textView5 = (TextView) findViewById(R.id.textView5);

// size stores the number entered by user
RelativeLayout myLayout = (RelativeLayout)findViewById(R.id.layout1);

// Creating a new TextView
TextView[] tv = new TextView[size+1];
TextView temptv;

for (i = 1; i <= size; i++) {
temptv = new TextView(MainActivity.this);
RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT);

if (i > 1) {
lp.addRule(RelativeLayout.BELOW, R.id.textView5);
lp.addRule(RelativeLayout.RIGHT_OF, tv[i-1].getId());
}
else {
lp.addRule(RelativeLayout.BELOW, R.id.textView5);
lp.addRule(RelativeLayout.ALIGN_LEFT, R.id.textView5);
}

// width of Text
temptv.setWidth(50);
// size of Text
temptv.setTextSize(TypedValue.COMPLEX_UNIT_SP, 25);

temptv.setLayoutParams(lp);
myLayout.addView(temptv, lp);

answer = "<font color='#8000ff'>" + mynum[i] + "</font>";
answer = answer + "&nbsp;&nbsp;&nbsp;";

// Update the label with our dynamic answer
temptv.setText(Html.fromHtml(answer));
tv[i] = temptv;
tv[i].setId(i);

}
setContentView(myLayout);


Is there a way to convert the android:background="@drawable/rounded_edges" to Java code so that I can still use the rounded_edges.xml to draw the circles? Or do I have to draw it completely from scratch in Java?



asked 1 min ago






Aucun commentaire:

Enregistrer un commentaire