尝试将视图设置为显示要显示ListView的文件(文本文件)时出现错误。我很确定它与 XML 有关。我只想显示来自 的信息this.file = fileop.ReadFileAsList("Installed_packages.txt");。我的代码:
ListView
this.file = fileop.ReadFileAsList("Installed_packages.txt");
public class Main extends Activity { private TextView tv; private FileOperations fileop; private String[] file; /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); this.fileop = new FileOperations(); this.file = fileop.ReadFileAsList("Installed_packages.txt"); setContentView(R.layout.main); tv = (TextView) findViewById(R.id.TextView01); ListView lv = new ListView(this); lv.setTextFilterEnabled(true); lv.setAdapter(new ArrayAdapter<String>(this, R.layout.list_item, this.file)); lv.setOnItemClickListener(new AdapterView.OnItemClickListener() { public void onItemClick(AdapterView<?> parent, View view, int position, long id) { // When clicked, show a toast with the TextView text Toast.makeText(getApplicationContext(), ((TextView) view).getText(), Toast.LENGTH_SHORT).show(); } }); setContentView(lv); } }
list_item.xml :
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="fill_parent" android:orientation="vertical" android:padding="10dp" android:textSize="16sp" android:textColor="#000"> </LinearLayout>
主.xml :
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="fill_parent" android:weightSum="1"> <ScrollView android:id="@+id/SCROLLER_ID" android:layout_width="fill_parent" android:layout_height="wrap_content" android:scrollbars="vertical" android:fillViewport="true"> <TextView android:layout_width="fill_parent" android:layout_height="wrap_content" android:padding="5sp" android:id="@+id/TextView01" android:text="@string/hello"/> </ScrollView> </LinearLayout>
ArrayAdapter 要求资源 ID 是 TextView XML 异常意味着您不提供ArrayAdapter预期的内容。当您使用此构造函数时:
ArrayAdapter
new ArrayAdapter<String>(this, R.layout.a_layout_file, this.file)
R.Layout.a_layout_file必须是仅包含 a 的 xml 布局文件的 id TextView(TextView 不能 被另一个布局包装,例如 aLinearLayout等RelativeLayout!),如下所示:
R.Layout.a_layout_file
TextView
LinearLayout
RelativeLayout
<?xml version="1.0" encoding="utf-8"?> <TextView xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="wrap_content" // other attributes of the TextView />
如果你想让你的列表行布局有点不同,那么一个简单的TextView小部件使用这个构造函数:
new ArrayAdapter<String>(this, R.layout.a_layout_file, R.id.the_id_of_a_textview_from_the_layout, this.file)
您提供id可以包含各种视图的布局的位置,但还 必须 包含传递给您的TextViewwith 和(第三个参数),以便它可以知道在行布局中放置的位置。id``ArrayAdapter``Strings
id
id``ArrayAdapter``Strings