以编程方式访问rowlistview

时间:2013-01-24 00:01:55

标签: android

我正在尝试以编程方式更改ListView中文本的对齐方式,而不是更改xml文件。

这是我的row_listview.xml

<?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/textViewRowList" 
    android:layout_height="?android:attr/listPreferredItemHeight"
    android:layout_width="fill_parent"
    android:textSize="20sp"
    android:paddingLeft="6dip"
    android:paddingRight="6dip" 
    android:gravity="left" 
    android:textColor="#330033"
    android:textStyle="bold"/>

activity_main.xml已定义ListView

<ListView
    android:id="@+id/listView1"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:divider="@null"
    android:dividerHeight="0dp"
    tools:listitem="@android:layout/simple_list_item_1" 
    android:background= "#FF6600">
 </ListView>

所以在我的mainactivity.java中,当用户点击我的活动上的按钮时,我试图在运行时更改listview中文本的对齐

private ListView lv;
private TextView tvRowListView;
lv.setAdapter(new ArrayAdapter<String>(this,R.layout.row_listview, sampleStringArray));
tvRowListView = (TextView) findViewById(R.id.textViewRowList);
tvRowListView.setGravity(Gravity.CENTER);

然而,上面的最后一行是抛出nullpointerexception。我不知道为什么。有人可以在这里提出一些想法/解决方案。

1 个答案:

答案 0 :(得分:0)

您的textViewRowList对于该列表中的每个项目都存在,如果您想要更改它的属性,您需要在Adapter getView中执行此操作,这意味着您需要创建自定义适配器< / p>

相关问题