以编程方式创建ListView

ash*_*raf 13 android listview

嗨,我是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);
    }
}
Run Code Online (Sandbox Code Playgroud)

moo*_*ese 20

这是一个不需要你编写任何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();
Run Code Online (Sandbox Code Playgroud)

  • 忽略对话框的东西.您可以调整它以使用ListActivity. (2认同)

Kev*_*haw 0

public class ListApp extends ListActivity
Run Code Online (Sandbox Code Playgroud)