.
MyBuddies01 ListView OnClickListener
1) Create New Empty Project
2) Edit Layout (activity_main.xml)
<?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:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.notarazi.mybuddies01.MainActivity">
<Button
android:id="@+id/btn_add_buddy"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Add Buddy"/>
<ListView
android:id="@+id/lvw_buddies"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:entries="@array/buddies_array" />
</LinearLayout>
|
3) Add Resource (buddies_array)
<resources>
<string name="app_name">MyBuddies</string>
<string-array name="buddies_array">
<item>Superman</item>
<item>Batman</item>
<item>Spiderman</item>
<item>Utraman</item>
<item>Ironman</item>
</string-array>
</resources>
|
4) Edit Controller (MainActivity.java)
package com.notarazi.mybuddies01;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
ListView lvwBuddies;
Button btnAddBuddy;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
setLvwBuddies();
setBtnAddBuddy();
}
private void setLvwBuddies() {
lvwBuddies = (ListView) findViewById(R.id.lvw_buddies);
lvwBuddies.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position,long id) {
editBuddy(position, ((TextView) view).getText().toString());
}
});
}
private void setBtnAddBuddy() {
btnAddBuddy=(Button) findViewById(R.id.btn_add_buddy);
btnAddBuddy.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
addBuddy();
}
});
}
private void addBuddy() {
Toast.makeText(getApplicationContext(),"Add Buddy",
Toast.LENGTH_SHORT).show();
}
private void editBuddy(int position, String text) {
Toast.makeText(getApplicationContext(),"Edit Buddy.\nPosition:"+position+"\nText:"+text+"\n",
Toast.LENGTH_SHORT).show();
}
}
|
DOWNLOAD
.
No comments:
Post a Comment