activity_main.xml
Java Android 2017
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:id="@+id/activity_main" android:orientation="vertical" android:layout_width="match_parent" android:layout_height="match_parent"> <ListView //Nhận value từ adapter thông qua id android:id="@+id/lv_name" android:layout_weight="1" android:backgroundTint="#82ffd5" android:background="#FFF" android:layout_width="match_parent" android:layout_height="wrap_content" /> <ListView android:id="@+id/lv_city" android:layout_weight="1" android:background="#bcfcf8a6" android:layout_width="match_parent" android:layout_height="wrap_content" //Nhận value từ file xml thông qua name android:entries="@array/country_arrays" android:prompt="@string/country_prompt" /> </LinearLayout>
MainActivity.java
Java Android 2017
package com.example.lonely.listviewclick; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.Gravity; import android.view.View; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.ListView; import android.widget.Toast; import java.util.ArrayList; import java.util.List; public class MainActivity extends AppCompatActivity implements AdapterView.OnItemClickListener { private ListView lvName; private List<String> list; private ListView lvCity; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); lvName = (ListView) findViewById(R.id.lv_name); lvCity = (ListView) findViewById(R.id.lv_city); //Cách 1 list = new ArrayList<>(); list.add("Java"); list.add("Android"); list.add("PHP"); list.add("C#"); list.add("ASP.NET"); //Cách 1 set value cho ListView với adapter ArrayAdapter<String> adapter = new ArrayAdapter(this, android.R.layout.simple_spinner_item, list); lvName.setAdapter(adapter); lvName.setOnItemClickListener(this); lvCity.setOnItemClickListener(this); } @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { switch (parent.getId()) { case R.id.lv_name: Toast toast = Toast.makeText(getApplicationContext(), list.get(position), Toast.LENGTH_SHORT); toast.setGravity(Gravity.TOP | Gravity.TOP, 0, 350); toast.show(); break; case R.id.lv_city: String selectedFromList =(lvCity.getItemAtPosition(position).toString()); Toast.makeText(this, selectedFromList, Toast.LENGTH_SHORT).show(); break; default: break; } } }
strings.xml
Java Android 2017
<resources> <string name="app_name">ListViewClick</string> //Cách 2 set value cho ListView với xml <string name="country_prompt">Chọn Tỉnh/Thành Phố</string> <string-array name="country_arrays"> <item>Hà Nội</item> <item>Huế</item> <item>Sài Gòn</item> <item>Đà Nẵng</item> <item>Cần Thơ</item> </string-array> </resources>
0 nhận xét:
Post a Comment