1. First create a new AndroidProject
Click Next to proceed to the next step
Next,
Create an Empty Activity
Next
Finish, and then run it on the virtual machine, so that an empty AndroidProject is created
Two: Next, let's see how to add ListView
1. Switch the Project mode to Android
Double-click activity_main.xml, and then delete the TextView that comes with the project creation
Then, find RelativeLayout under Legacy and drag it into ComponentTree
Change the ID to RL_01,
Then find ListView in Legacy, and drag ListView to the RL_01 component
Write code
public class MainActivity extends AppCompatActivity {
//定义一个listView
ListView listView ;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//通过Id获取到ListView
listView = (ListView)findViewById(R.id.LV_01);
//定义一个ArrayList
final ArrayList<String> arrayList = new ArrayList<>();
//在ArrayList中填充模拟数据
arrayList.add("Item_1");
arrayList.add("Item_2");
arrayList.add("Item_3");
arrayList.add("Item_4");
arrayList.add("Item_5");
arrayList.add("Item_6");
arrayList.add("Item_7");
arrayList.add("Item_8");
arrayList.add("Item_9");
arrayList.add("Item_10");
arrayList.add("Item_11");
arrayList.add("Item_12");
arrayList.add("Item_13");
arrayList.add("Item_14");
arrayList.add("Item_15");
//定义ArrayAdapter1
ArrayAdapter<String> adapter = new ArrayAdapter( this,R.layout.support_simple_spinner_dropdown_item,arrayList);
//设置listView
listView.setAdapter(adapter);
}
Run as shown in the figure:
However, at this time, the Item has not clicked on the corresponding event. Next, add the corresponding event to him
//设置listView
listView.setAdapter(adapter);
//设置点击时间
listView.setOnItemClickListener(new AdapterView.OnItemClickListener(){
@Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l)
{
Toast.makeText(MainActivity.this,"click item"+i+" "+arrayList.get(i).toString(),Toast.LENGTH_SHORT).show();
}
});
run as follows
Such a simple ListViewDemo is complete