Change TextView-object in a custom view

890 views Asked by At

I cannot understand why I cannot change/manipulate a view (i.e. textview) in a class that extends view. I can only "do things" in the xml but not make any changes in the custom view. In that class I have inflated the xml-file and the compiler does not complain. Its just that - nothing happends if i want to use the setText-method.

the xml-file

<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/scrollView1"
android:layout_width="720dp"
android:layout_height="1250dp"
android:layout_marginLeft="0dp" >
<LinearLayout
    android:id="@+id/layout"
    android:layout_width="match_parent"
    android:layout_height="1250dp"
    android:orientation="vertical">

     <TextView
    android:id="@+id/theTextView"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text = "here I am changeable :-)"/>     

 </LinearLayout>   

 public class DrawChart extends View {

   private TextView tv;

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


     LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        View view = inflater.inflate(R.layout.activity_main, new LinearLayout(context), true);

     tv = (TextView) view.findViewById(R.id.theTextView);
     tv.setText("I would like to be changed here :-(");


.....

@Override
protected void onDraw(Canvas canvas) {

  ..... // custom drawings here

main-class

 public class MainActivity extends ActionBarActivity {

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

    DrawChart dc = new DrawChart(this);

    LinearLayout layout = (LinearLayout) findViewById(R.id.layout);
    layout.addView(dc);

}

So - what am I doing wrong?

Edit: I have even tried the following - but I doesnt work neither

 LinearLayout ll = (LinearLayout) view.findViewById(R.id.layout);
    ll.removeView(tv);
    tv.setText("jfjgjfgjfjg");
    ll.addView(tv);

Edit: I solved it in another way: Instead I passed the textView from the MainActivity to the DrawCharts constructor - then it works just fine :-) So something is wrong with the inflating of the xml. I Would rather use the first approach so feel free to answer this question what is wrong with the inflating, thanks!!

0

There are 0 answers