ListView with own layout

ListView with own layout Example

MainCLASS

package com.example.malik.test;

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {

ListView listView;
ArrayAdapter<String> adapter;
String[] android_versions = { “version1”, “version2”, “version3”, “version4”, “version5”, “version6”,
“version7”, “version8”, “version9”, “version10″ };

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

listView = (ListView) findViewById(R.id.listView);
adapter = new ArrayAdapter<String>(this, R.layout.list_view_custom_layout, R.id.list_item, android_versions);
listView.setAdapter(adapter);

listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Toast.makeText(getApplicationContext(), parent.getItemAtPosition(position) + ” is selected”, Toast.LENGTH_SHORT).show();
}
});

}
}

MainXML

<?xml version=”1.0″ encoding=”utf-8″?>
<RelativeLayout xmlns:android=”http://schemas.android.com/apk/res/android”
xmlns:tools=”http://schemas.android.com/tools”
android:layout_width=”match_parent”
android:layout_height=”match_parent”
android:paddingBottom=”@dimen/activity_vertical_margin”
android:paddingLeft=”@dimen/activity_horizontal_margin”
android:paddingRight=”@dimen/activity_horizontal_margin”
android:paddingTop=”@dimen/activity_vertical_margin”
tools:context=”com.example.malik.test.MainActivity”>
<ListView
android:layout_width=”wrap_content”
android:layout_height=”wrap_content”
android:id=”@+id/listView”
android:layout_alignParentTop=”true”
android:layout_alignParentLeft=”true”
android:layout_alignParentStart=”true”

/>
</RelativeLayout>

 

list_view_custom_layout XML

<?xml version=”1.0″ encoding=”utf-8″?>
<LinearLayout xmlns:android=”http://schemas.android.com/apk/res/android”
android:orientation=”vertical” android:layout_width=”match_parent”
android:layout_height=”match_parent”>

<TextView
android:layout_width=”match_parent”
android:layout_height=”wrap_content”
android:id=”@+id/list_item”
android:text=”Hello World”
android:padding=”15dp”
android:background=”#ffff00″
android:textAppearance=”?android:textAppearanceLarge”
android:textColor=”#0818F8″
android:gravity=”center”
/>

</LinearLayout>

 

Output :

demo

 

Share

Leave a Reply

Your email address will not be published. Required fields are marked *

Time limit is exhausted. Please reload CAPTCHA.