Advanced Adapter in Android with Example
Here is source code of the Program to create an Adapter in an Application. The program is successfully compiled and run on a Windows system using Eclipse Ide. The program output is also shown below.
1. MainActivity.java:
import android.os.Bundle;
import android.app.Activity;
import android.app.ListActivity;
import android.view.Menu;
public class MainActivity extends ListActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
String str[] = new String[] {"C","C++","Java","Andorid"};
AdvancedAdapter adapter = new AdvancedAdapter(this, str);
setListAdapter(adapter);
}
}
2. AdvancedAdapter:
import java.util.zip.Inflater;
import android.app.Activity;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.TextView;
public class AdvancedAdapter extends ArrayAdapter<String> {
private final Context context;
private final String[] lang;
public AdvancedAdapter(Context context, String lang[]) {
super(context, R.layout.rowlayout, lang);
// TODO Auto-generated constructor stub
this.context = context;
this.lang = lang;
}
static class Holder {
public TextView text;
public ImageView img;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
View row;
if (convertView == null) {
LayoutInflater li = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
row = li.inflate(R.layout.rowlayout, parent, false);
Holder holder = new Holder();
holder.text = (TextView) row.findViewById(R.id.label);
holder.img = (ImageView) row.findViewById(R.id.icon);
row.setTag(holder);
} else {
row = convertView;
}
Holder holder = (Holder) row.getTag();
String str = lang[position];
holder.text.setText(str);
if (str.startsWith("C")) {
holder.img.setImageResource(R.drawable.c_pic);
} else if (str.startsWith("Java")) {
holder.img.setImageResource(R.drawable.java);
} else if (str.startsWith("Android")) {
holder.img.setImageResource(R.drawable.ic_launcher);
} else {
// c++
holder.img.setImageResource(R.drawable.c_prog);
}
return row;
}
}
3. RowLayout.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content" >
<ImageView
android:id="@+id/icon"
android:layout_width="100px"
android:layout_height="100px"
android:layout_marginLeft="4px"
android:layout_marginRight="10px"
android:layout_marginTop="4px"
android:src="@drawable/ic_launcher" >
</ImageView>
<TextView
android:id="@+id/label"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@+id/label"
android:textSize="80px" >
<extView>
</LinearLayout>
No comments:
Post a Comment