gareth power gareth power - 5 months ago 16
Android Question

Why won't my TextView add to RelativeLayout?

I am trying to add my textView to my app programmatically, but it doesn't appear when I run it.I put a button in the XML to test the relativeLayout and it appears fine, but the textView doesn't so I'm putting down to code? my code is below. Thanks in advance!

@Override
public void onResponse(String response) {
StringX = response;
Log.e("RESPONSE", response);

TextView valueTV = new TextView(getBaseContext());
valueTV.setText("Hello!");
valueTV.setTextSize(20);
RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(
RelativeLayout.LayoutParams.WRAP_CONTENT,
RelativeLayout.LayoutParams.WRAP_CONTENT);
valueTV.setLayoutParams(params);
valueTV.setTextColor(Color.argb(1, 0, 95, 0));
valueTV.setId(0);
scrollerF.addView(valueTV);
}


And my layout:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.example.garethpower92.tourlink_ireland.coupons">


<ScrollView
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:paddingTop="70dp"
android:background="#FFFFFF"
android:id="@+id/scrollerMain"
android:layout_below="@+id/textView"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:fillViewport="false">
<RelativeLayout
android:id="@+id/rlX"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
>


</RelativeLayout>
</ScrollView>


<TextView
android:layout_width="fill_parent"
android:layout_height="70dp"
android:text="Discounts"
android:id="@+id/textView"
android:textColor="#FFFFFF"
android:textSize="40sp"
android:background="#009500"
android:textAlignment="center"
android:paddingTop="10sp"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_alignParentTop="true" />


</RelativeLayout>

Answer

Below code works for me, In your activity onCreate method add this code:

    @Override
 protected void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.activity_main);
      TextView mTextv = new TextView(getApplicationContext());
      mTextv.setText("This is Text....!!");
      mTextv.setGravity(Gravity.CENTER_VERTICAL);
      linearLayout = (LinearLayout) findViewById(R.id.lLayout);
        mTextv.setTextSize(20);
      mTextv.setTypeface(Typeface.MONOSPACE);
      mTextv.setTextColor(Color.parseColor("#454045"));
        linearLayout.addView(mTextv);
 }

Linear layout is the parent layout of TextView you'll add dynamically, so ad textview as child view in linearLayout object.

Comments