android.widget.LinearLayout cannot be cast to android.widget.TextView

android, android-layout, android-listview

Solution

Your row is a `TextView` wrapped by a `LinearLayout` so you might want to do this:

LinearLayout ll = (LinearLayout) view; // get the parent layout view
TextView tv = (TextView) ll.findViewById(R.id.contents); // get the child text view
final String text = tv.getText().toString();

Problem

I add a `ListView` on runtime like this: ``` MainMenue = getResources().getStringArray(R.array.Unit); // remove all controls LinearLayout formLayout = (LinearLayout)findViewById(R.id.submenue); formLayout.removeAllViews(); menueview = new ListView(getApplicationContext()); menueview.setVisibility(ListView.VISIBLE); LinearLayout.LayoutParams params = new LinearLayout.LayoutParams( LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT); params.gravity = Gravity.RIGHT; menueview.setLayoutParams(params); menueview.setAdapter(new submenueadapter(menueview.getContext(), MainMenue)); // Set the on Item SetMenueOnClick() ; formLayout.addView(menueview); ``` and then I add a item click listener like this: ``` public void SetMenueOnClick() { menueview.setOnItemClickListener(new OnItemClickListener() { public void onItemClick(AdapterView<?> parent, View view, int position, long id) { final String text = (String) ((TextView)view).getText(); } }); } ``` But then I have an error: ``` 06-03 10:59:25.862: E/AndroidRuntime(14732): at android.view.ViewRoot.handleMessage(ViewRoot.java:2109) android.widget.LinearLayout cannot be cast to android.widget.TextView ``` at this line: ``` final String text = (String) ((TextView)view).getText(); ``` Any idea how to get the text in this issue? the adapter looks like this: ``` public View getView(int position, View convertView, ViewGroup parent) { LayoutInflater inflater = (LayoutInflater) context .getSystemService(Context.LAYOUT_INFLATER_SERVICE); View rowView = inflater.inflate(R.layout.shortmenue, parent, false); TextView textView = (TextView) rowView.findViewById(R.id.contents); textView.setText(values[position]); // Change icon based on name String s = values[position]; System.out.println(s); rowView.setBackgroundResource(R.drawable.alternate_list_color); return rowView; } ``` and `R.layout.shortmenue` is simple, only a `TextView` like below: ``` <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="wrap_content" android:layout_height="wrap_content" android:orientation="vertical" > <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/contents" android:textSize="34dp" /> </LinearLayout> ```

Original source