在Xamarin
我想在ListVIew中添加一个简单的TextView,但不确定代码是否正确。
这是我目前的代码:
protected override void OnCreate (Bundle bundle)
{
base.OnCreate (bundle);
SetContentView (Resource.Layout.Main);
ListView listView = new ListView(this.ApplicationContext);
TextView textView = new TextView (this.ApplicationContext);
textView.Text = "Example text";
View view = new View (this.ApplicationContext);
}
我可以请一些帮助吗?
修改
这是我的代码:
protected override void OnCreate (Bundle bundle)
{
base.OnCreate (bundle);
ListView lst = (ListView) FindViewById(Resource.Id.listView);
// create the ArrayList to store the titles of nodes
List<String> listItems = new List<String>();
listItems.Add ("Test 1");
listItems.Add ("Test 2");
ArrayAdapter ad = new ArrayAdapter(this.ApplicationContext, Resource.Layout.simple_list_item_1, listItems);
// give adapter to ListView UI element to render
lst.SetAdapter(ad);
}
我收到此错误:
UNHANDLED EXCEPTION: System.NullReferenceException: Object reference not set to an instance of an object
我可以帮忙看一下这段代码吗?
提前致谢
答案 0 :(得分:1)
如果它是一个简单的textView List,那么使用它:
ListView lst = (ListView) findViewById(R.id.listView);
// create the ArrayList to store the titles of nodes
ArrayList<String> listItems = new ArrayList<String>();
然后在ArrayList listItems中添加所有文本 然后使用以下方法
ArrayAdapter ad = new ArrayAdapter(ListActivity.this,
android.R.layout.simple_list_item_1, listItems);
// give adapter to ListView UI element to render
lst.setAdapter(ad);
XML文件:
<LinearLayout 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=".DisplayMessageActivity"
android:orientation="vertical">
<ListView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/listView"
android:smoothScrollbar="true"
android:fastScrollAlwaysVisible="false"
android:layout_centerHorizontal="true"
android:layout_gravity="center"/>
</LinearLayout>
答案 1 :(得分:0)
答案 2 :(得分:0)
如果您只想在ListView中显示一些字符串:
声明以下变量:
private ArrayList<String> _listEntrys = new ArrayList<String>(); // String-ArrayList for storing the itmes that should be shown in the list
private ArrayAdapter<String> _arrayAdapter; // Arrayadapter to fill your list
你的OnCreate应该是这样的:
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Create ListView
ListView listView = new ListView(this.ApplicationContext);
// Set Array-Adapter
_arrayAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, _listEntrys);
listview.setAdapter(m_ArrayAdapter);
listview.setOnItemClickListener(this);
// Add here your desired List-Items
_listEntrys.add("your string");
_arrayAdapter.notifyDataSetChanged(); // Call this everytime you change the values in the ArrayList to refresh the view
}