嗨,我是Android新手。谁能告诉我请问以下代码是错的:
public class ListApp extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
TextView lText = new TextView(this);
lText.setId(0);
ListView lView = new ListView(this);
String[] lStr = new String[]{"AA","BB", "CC"};
ArrayAdapter lAdap = new ArrayAdapter(this,lText.getId(),lStr);
lView.setAdapter(lAdap);
lView.setFocusableInTouchMode(true);
setContentView(lView);
}
}
答案 0 :(得分:19)
这是一个不需要你编写任何xml布局的解决方案。它尽可能使用标准的android布局,不需要通货膨胀:
Dialog dialog = new Dialog(this);
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Select Color Mode");
ListView modeList = new ListView(this);
String[] stringArray = new String[] { "Bright Mode", "Normal Mode" };
ArrayAdapter<String> modeAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, android.R.id.text1, stringArray);
modeList.setAdapter(modeAdapter);
builder.setView(modeList);
dialog = builder.create();
答案 1 :(得分:3)
试试这个..
将以下代码粘贴到list_item.xml中。
<?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="fill_parent"
android:padding="10dp"
android:textSize="16sp" android:textColor="#ffffff" android:textStyle="bold" android:background="@drawable/border_cell">
</TextView>
这是活动类....
public class UsersListActivity extends ListActivity{
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
String[] statesList = {"listItem 1", "listItem 2", "listItem 3"};
setListAdapter(new ArrayAdapter<String>(this, R.layout.list_item,
statesList));
ListView lv = getListView();
lv.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
Toast.makeText(getApplicationContext(),
"You selected : "+((TextView) view).getText(), Toast.LENGTH_SHORT).show();
}
});
}
}
答案 2 :(得分:1)
最佳做法是分离视图(xml布局)和控制器(活动)。
如果你不想要这个,试着把
setContentView(lView);
在 onCreate
的开头答案 3 :(得分:0)
public class ListApp extends ListActivity
答案 4 :(得分:0)
使用listview制作布局XML文件,并在首次将内容视图设置为布局后使用findViewById设置适配器