我在運行時添加一個ListView
這樣的:android.widget.LinearLayout不能轉換爲android.widget.TextView
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);
,然後我添加了一個項目點擊收聽這樣的:
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();
}
});
}
但後來我有一個錯誤:
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
在這一行:
final String text = (String) ((TextView)view).getText();
任何想法如何獲得在這個問題的文字?適配器看起來是這樣的:
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;
}
和R.layout.shortmenue
簡單,只有一個TextView
象下面這樣:
<?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>
工作!愚蠢:P –
或者只是試着打重建按鈕 –