View

Tuesday, 24 May 2011

Static TableLayout

The TableLayout is built using the TableLayout and the TableRow commands. There is no TableCols like the <td> tag in HTML. To align your view in columns you have to set the width of the elements and manually control the layout.
<TableLayout android:id="@+id/TableLayout01" android:layout_width="fill_parent" android:layout_height="wrap_content"  android:stretchColumns="0">

  <TableRow android:id="@+id/TableRow01" android:layout_width="wrap_content" android:layout_height="wrap_content">
    <TextView android:id="@+id/TextView01" android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="textfield 1-1"></TextView>

    <CheckBox android:id="@+id/CheckBox01" android:layout_width="wrap_content" android:layout_height="wrap_content"></CheckBox>
  </TableRow>

  <TableRow android:id="@+id/TableRow02" android:layout_width="wrap_content" android:layout_height="wrap_content">
    <TextView android:id="@+id/TextView03" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="textfield 2-1"></TextView>
    <TextView android:id="@+id/TextView04" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="textfield 2-2"></TextView>
  </TableRow>

</TableLayout>
<TableLayout android:id="@+id/tableLayout1" android:layout_height="wrap_content" android:layout_width="match_parent">
    <TableRow android:id="@+id/tableRow1" android:layout_width="wrap_content" android:layout_height="wrap_content">
        <Button android:text="Button" android:id="@+id/button1" android:layout_width="wrap_content" android:layout_height="wrap_content"></Button>
        <RadioButton android:text="RadioButton" android:id="@+id/radioButton1" android:layout_width="wrap_content" android:layout_height="wrap_content"></RadioButton>
        <ProgressBar android:layout_height="wrap_content" android:id="@+id/progressBar1" android:layout_width="wrap_content"></ProgressBar>
    </TableRow>
</TableLayout>
<TableLayout android:id="@+id/tableLayout2" android:layout_height="wrap_content" android:layout_width="match_parent">
    <TableRow android:layout_height="wrap_content" android:layout_width="match_parent" android:id="@+id/tableRow2">
        <SeekBar android:layout_height="wrap_content" android:id="@+id/seekBar1" android:layout_width="fill_parent"></SeekBar>
        <DigitalClock android:text="DigitalClock" android:id="@+id/digitalClock1" android:layout_width="wrap_content" android:layout_height="wrap_content"></DigitalClock>
        <ZoomButton android:src="@android:drawable/btn_plus" android:layout_height="wrap_content" android:layout_width="wrap_content" android:id="@+id/zoomButton1"></ZoomButton>
        <ToggleButton android:text="ToggleButton" android:id="@+id/toggleButton1" android:layout_width="wrap_content" android:layout_height="wrap_content"></ToggleButton>
    </TableRow>
</TableLayout>
<TableLayout android:id="@+id/tableLayout3" android:layout_height="wrap_content" android:layout_width="match_parent" android:stretchColumns="0">
    <TableRow android:id="@+id/tableRow3" android:layout_width="wrap_content" android:layout_height="wrap_content">
        <SeekBar android:layout_height="wrap_content" android:id="@+id/seekBar2" android:layout_width="fill_parent"></SeekBar>
    </TableRow>
</TableLayout>


How To Add a Row Dynamically

 whenever the button is clicked, it adds a new row to the TableLayout and notice the Scrollbar from the ScrollView.

XML CODE:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent" android:orientation="vertical">

<Button android:id="@+id/Button01" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Click To Add New row"></Button>

<ScrollView android:id="@+id/ScrollView01" android:layout_width="wrap_content" android:layout_height="wrap_content">

  <TableLayout android:id="@+id/TableLayout01" android:layout_width="fill_parent" android:layout_height="wrap_content" android:stretchColumns="0">

    <TableRow android:id="@+id/TableRow01" android:layout_width="wrap_content" android:layout_height="wrap_content">
        <TextView android:layout_width="fill_parent" android:text="textfield 1-1" android:layout_height="wrap_content" android:id="@+id/TextView01"></TextView>
        <ImageView android:id="@+id/imageView1" android:layout_height="wrap_content" android:src="@drawable/icon" android:layout_width="wrap_content"></ImageView>
      <DigitalClock android:text="DigitalClock" android:layout_width="wrap_content" android:id="@+id/digitalClock1" android:layout_height="wrap_content"></DigitalClock>
      <CheckBox android:id="@+id/CheckBox01" android:text="" android:layout_width="wrap_content" android:layout_height="wrap_content"></CheckBox>
    </TableRow>

  </TableLayout>
</ScrollView>
</LinearLayout>

Tuesday, 17 May 2011

How to use calendar in android


In this apps we use four class to run calendarview.
first class name as CalendarActivity,Cell,TestActivity,calendarView.Before that we download a images like background.png,calendar_week.png,typeb_calendar_today.png. insert into Drawable folder,because to show and set a day in calendar format .





 






package com.exina.android.calendar;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.text.format.DateUtils;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

public class CalendarActivity extends Activity  implements CalendarView.OnCellTouchListener{
public static final String MIME_TYPE = "vnd.android.cursor.dir/vnd.exina.android.calendar.date";
CalendarView mView = null;
TextView mHit;
Handler mHandler = new Handler();
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        mView = (CalendarView)findViewById(R.id.calendar);
        mView.setOnCellTouchListener(this);
        
        if(getIntent().getAction().equals(Intent.ACTION_PICK))
        findViewById(R.id.hit).setVisibility(View.INVISIBLE);
    }

public void onTouch(Cell cell) {
Intent intent = getIntent();
String action = intent.getAction();
if(action.equals(Intent.ACTION_PICK) || action.equals(Intent.ACTION_GET_CONTENT)) {
Intent ret = new Intent();
ret.putExtra("year", mView.getYear());
ret.putExtra("month", mView.getMonth());
ret.putExtra("day", cell.getDayOfMonth());
this.setResult(RESULT_OK, ret);
finish();
return;
}
int day = cell.getDayOfMonth();
if(mView.firstDay(day))
mView.previousMonth();
else if(mView.lastDay(day))
mView.nextMonth();
else
return;

mHandler.post(new Runnable() {
public void run() {
Toast.makeText(CalendarActivity.this, DateUtils.getMonthString(mView.getMonth(), DateUtils.LENGTH_LONG) + " "+mView.getYear(), Toast.LENGTH_SHORT).show();
}
});
}

    
}



import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Rect;
import android.graphics.RectF;
import android.graphics.drawable.Drawable;
import android.util.Log;

public class Cell {
private static final String TAG = "Cell";
protected Rect mBound = null;
protected int mDayOfMonth = 1; // from 1 to 31
protected Paint mPaint = new Paint(Paint.SUBPIXEL_TEXT_FLAG
            |Paint.ANTI_ALIAS_FLAG);
int dx, dy;
public Cell(int dayOfMon, Rect rect, float textSize, boolean bold) {
mDayOfMonth = dayOfMon;
mBound = rect;
mPaint.setTextSize(textSize/*26f*/);
mPaint.setColor(Color.BLACK);
if(bold) mPaint.setFakeBoldText(true);
dx = (int) mPaint.measureText(String.valueOf(mDayOfMonth)) / 2;
dy = (int) (-mPaint.ascent() + mPaint.descent()) / 2;
}
public Cell(int dayOfMon, Rect rect, float textSize) {
this(dayOfMon, rect, textSize, false);
}
protected void draw(Canvas canvas) {
canvas.drawText(String.valueOf(mDayOfMonth), mBound.centerX() - dx, mBound.centerY() + dy, mPaint);
}
public int getDayOfMonth() {
return mDayOfMonth;
}
public boolean hitTest(int x, int y) {
return mBound.contains(x, y); 
}
public Rect getBound() {
return mBound;
}
public String toString() {
return String.valueOf(mDayOfMonth)+"("+mBound.toString()+")";
}
}




import java.text.SimpleDateFormat;
import java.util.Calendar;

import android.app.AlertDialog;
import android.content.Intent;
import android.os.Bundle;
import android.preference.Preference;
import android.preference.PreferenceActivity;
import android.widget.Toast;

public class TestActivity extends PreferenceActivity implements Preference.OnPreferenceClickListener{
@Override
public void onCreate(Bundle savedInstance) {
super.onCreate(savedInstance);
addPreferencesFromResource(R.xml.test);
findPreference("show").setIntent(new Intent(Intent.ACTION_VIEW).setDataAndType(null, CalendarActivity.MIME_TYPE));
findPreference("pick").setOnPreferenceClickListener(this);
findPreference("about").setOnPreferenceClickListener(this);
}
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if(resultCode==RESULT_OK) {
int year = data.getIntExtra("year", 0);
int month = data.getIntExtra("month", 0);
int day = data.getIntExtra("day", 0);
final Calendar dat = Calendar.getInstance();
dat.set(Calendar.YEAR, year);
dat.set(Calendar.MONTH, month);
dat.set(Calendar.DAY_OF_MONTH, day);
SimpleDateFormat format = new SimpleDateFormat("yyyy MMM dd");
Toast.makeText(TestActivity.this, format.format(dat.getTime()), Toast.LENGTH_LONG).show();
}
}
public boolean onPreferenceClick(Preference  preference) {
String key = preference.getKey();
if(key.equals("pick")) {
startActivityForResult(new Intent(Intent.ACTION_PICK).setDataAndType(null, CalendarActivity.MIME_TYPE), 100);
} else if(key.equals("about")) {
new AlertDialog.Builder(this).setIcon(android.R.drawable.ic_dialog_alert).setTitle(R.string.app_name).setMessage("http://saga-androidapplication.webgarden.com/\n\nBy Saga<arun.saga@yahoo.in>").create().show();
}
return true;
}
}

import java.util.Calendar;

import android.content.Context;
import android.content.res.Resources;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Rect;
import android.graphics.drawable.Drawable;
import android.util.AttributeSet;
import android.util.MonthDisplayHelper;
import android.view.MotionEvent;
import android.widget.ImageView;

public class CalendarView extends ImageView {
    private static int WEEK_TOP_MARGIN = 74;
    private static int WEEK_LEFT_MARGIN = 40;
    private static int CELL_WIDTH = 58;
    private static int CELL_HEIGH = 53;
    private static int CELL_MARGIN_TOP = 92;
    private static int CELL_MARGIN_LEFT = 39;
    private static float CELL_TEXT_SIZE;
    
private static final String TAG = "CalendarView"; 
private Calendar mRightNow = null;
    private Drawable mWeekTitle = null;
    private Cell mToday = null;
    private Cell[][] mCells = new Cell[6][7];
    private OnCellTouchListener mOnCellTouchListener = null;
    MonthDisplayHelper mHelper;
    Drawable mDecoration = null;
    
public interface OnCellTouchListener {
    public void onTouch(Cell cell);
    }

public CalendarView(Context context) {
this(context, null);
}
public CalendarView(Context context, AttributeSet attrs) {
this(context, attrs, 0);
}

public CalendarView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
mDecoration = context.getResources().getDrawable(R.drawable.typeb_calendar_today);
initCalendarView();
}
private void initCalendarView() {
mRightNow = Calendar.getInstance();
// prepare static vars
Resources res = getResources();
WEEK_TOP_MARGIN  = (int) res.getDimension(R.dimen.week_top_margin);
WEEK_LEFT_MARGIN = (int) res.getDimension(R.dimen.week_left_margin);
CELL_WIDTH = (int) res.getDimension(R.dimen.cell_width);
CELL_HEIGH = (int) res.getDimension(R.dimen.cell_heigh);
CELL_MARGIN_TOP = (int) res.getDimension(R.dimen.cell_margin_top);
CELL_MARGIN_LEFT = (int) res.getDimension(R.dimen.cell_margin_left);
CELL_TEXT_SIZE = res.getDimension(R.dimen.cell_text_size);
// set background
setImageResource(R.drawable.background);
mWeekTitle = res.getDrawable(R.drawable.calendar_week);
mWeekTitle.setBounds(WEEK_LEFT_MARGIN, WEEK_TOP_MARGIN, WEEK_LEFT_MARGIN+mWeekTitle.getMinimumWidth(), WEEK_TOP_MARGIN+mWeekTitle.getMinimumHeight());
mHelper = new MonthDisplayHelper(mRightNow.get(Calendar.YEAR), mRightNow.get(Calendar.MONTH));
initCells();
    }
private void initCells() {
   class _calendar {
    public int day;
    public boolean thisMonth;
    public _calendar(int d, boolean b) {
    day = d;
    thisMonth = b;
    }
    public _calendar(int d) {
    this(d, false);
    }
   };
   _calendar tmp[][] = new _calendar[6][7];
   
   for(int i=0; i<tmp.length; i++) {
    int n[] = mHelper.getDigitsForRow(i);
    for(int d=0; d<n.length; d++) {
    if(mHelper.isWithinCurrentMonth(i,d))
    tmp[i][d] = new _calendar(n[d], true);
    else
    tmp[i][d] = new _calendar(n[d]);
   
    }
   }

   Calendar today = Calendar.getInstance();
   int thisDay = 0;
   mToday = null;
   if(mHelper.getYear()==today.get(Calendar.YEAR) && mHelper.getMonth()==today.get(Calendar.MONTH)) {
    thisDay = today.get(Calendar.DAY_OF_MONTH);
   }
// build cells
Rect Bound = new Rect(CELL_MARGIN_LEFT, CELL_MARGIN_TOP, CELL_WIDTH+CELL_MARGIN_LEFT, CELL_HEIGH+CELL_MARGIN_TOP);
for(int week=0; week<mCells.length; week++) {
for(int day=0; day<mCells[week].length; day++) {
if(tmp[week][day].thisMonth) {
if(day==0 || day==6 )
mCells[week][day] = new RedCell(tmp[week][day].day, new Rect(Bound), CELL_TEXT_SIZE);
else 
mCells[week][day] = new Cell(tmp[week][day].day, new Rect(Bound), CELL_TEXT_SIZE);
} else
mCells[week][day] = new GrayCell(tmp[week][day].day, new Rect(Bound), CELL_TEXT_SIZE);
Bound.offset(CELL_WIDTH, 0); // move to next column 
// get today
if(tmp[week][day].day==thisDay) {
mToday = mCells[week][day];
mDecoration.setBounds(mToday.getBound());
}
}
Bound.offset(0, CELL_HEIGH); // move to next row and first column
Bound.left = CELL_MARGIN_LEFT;
Bound.right = CELL_MARGIN_LEFT+CELL_WIDTH;
}
}

    public void setTimeInMillis(long milliseconds) {
    mRightNow.setTimeInMillis(milliseconds);
    initCells();
    this.invalidate();
    }
        
    public int getYear() {
    return mHelper.getYear();
    }
    
    public int getMonth() {
    return mHelper.getMonth();
    }
    
    public void nextMonth() {
    mHelper.nextMonth();
    initCells();
    invalidate();
    }
    
    public void previousMonth() {
    mHelper.previousMonth();
    initCells();
    invalidate();
    }
    
    public boolean firstDay(int day) {
    return day==1;
    }
    
    public boolean lastDay(int day) {
    return mHelper.getNumberOfDaysInMonth()==day;
    }
    
    public void goToday() {
    Calendar cal = Calendar.getInstance();
    mHelper = new MonthDisplayHelper(cal.get(Calendar.YEAR), cal.get(Calendar.MONTH));
    initCells();
    invalidate();
    }
    
    public Calendar getDate() {
    return mRightNow;
    }
    
    @Override
    public boolean onTouchEvent(MotionEvent event) {
    if(mOnCellTouchListener!=null){
    for(Cell[] week : mCells) {
for(Cell day : week) {
if(day.hitTest((int)event.getX(), (int)event.getY())) {
mOnCellTouchListener.onTouch(day);
}
}
}
    }
    return super.onTouchEvent(event);
    }
  
    public void setOnCellTouchListener(OnCellTouchListener p) {
mOnCellTouchListener = p;
}

@Override
protected void onDraw(Canvas canvas) {
// draw background
super.onDraw(canvas);
mWeekTitle.draw(canvas);
// draw cells
for(Cell[] week : mCells) {
for(Cell day : week) {
day.draw(canvas);
}
}
// draw today
if(mDecoration!=null && mToday!=null) {
mDecoration.draw(canvas);
}
}
private class GrayCell extends Cell {
public GrayCell(int dayOfMon, Rect rect, float s) {
super(dayOfMon, rect, s);
mPaint.setColor(Color.LTGRAY);
}
}
private class RedCell extends Cell {
public RedCell(int dayOfMon, Rect rect, float s) {
super(dayOfMon, rect, s);
mPaint.setColor(0xdddd0000);
}
}

}
xml file name as main.xml.

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    >
<com.exina.android.calendar.CalendarView  android:id="@+id/calendar"
   android:layout_width="fill_parent" 
   android:layout_height="wrap_content" />
    <TextView android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:text="@string/app_name" />
    <TextView android:id="@+id/hit"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:text="@string/hit" />
   
</LinearLayout>



Go to AndroidManifest.xml .

package="com.exina.android.calendar"
      android:versionCode="1"
      android:versionName="1.0">
    <application android:icon="@drawable/icon" android:label="@string/app_name">
        <activity android:name=".CalendarActivity"
                  android:label="@string/app_name">
            
            <intent-filter>
                <action android:name="android.intent.action.PICK" />
                <category android:name="android.intent.category.DEFAULT" />
                <data android:mimeType="vnd.android.cursor.dir/vnd.exina.android.calendar.date" />
            </intent-filter>
            <intent-filter>
                <action android:name="android.intent.action.VIEW" />
                <category android:name="android.intent.category.DEFAULT" />
                <data android:mimeType="vnd.android.cursor.dir/vnd.exina.android.calendar.date" />
            </intent-filter>
        </activity>

    <activity android:label="@string/app_name"
     android:name=".TestActivity" android:icon="@drawable/icon">
    <intent-filter>
    <action android:name="android.intent.action.MAIN"/>
<category android:name="android.intent.category.LAUNCHER"/>
</intent-filter>
</activity>
</application>



Output:

 




Sunday, 15 May 2011

Samsung Nexus S 4G

The good: The Samsung Nexus S 4G offers a brilliant display, WiMax support, and agreeable performance. It gains a number of usability improvements from the Gingerbread OS, and its straight Google interface will appeal to Android purists.
The bad: The Samsung Nexus S 4G feels rather fragile, and it lacks a memory card slot and LED notifications. We were hoping for more new features over the Nexus One, and its 4G connection was spotty at times.
The bottom line: The Samsung Nexus S 4G offers a great combination of design, features, and performance. The 4G connection could be more reliable, but the Gingerbread OS, stock Android UI, and admirable call quality make for a satisfying smartphone.

Editors' note: Sprint's Samsung Nexus S 4G only differs from T-Mobile's Nexus S in a few ways. As such, we will focus on those differences for this review. For CNET's full analysis of the Nexus S series, including design and features, check our review of T-Mobile's handset.
As it has a habit of doing, Sprint grabbed the CTIA spotlight early this year when it announced the Samsung Nexus S 4G the day before the annual wireless confab convened in Florida. Though the device was hardly new to the cell phone

   

  







Manufacturer: Samsung.Part Number:SPHD720KIT..General
Product Type Smartphone With digital camera .Service Provider Sprint Nextel .Width 2.48 in .Depth 0.43 in .Height 4.88 in .Weight 4.55 oz .Body Color Black .Cellular
Technology CDMA/WiMax .Band WCDMA (UMTS) / GSM 850/900/1800/1900 .Phone Design PDA .Vibrating Alert Yes .Polyphonic Ringer Yes .Voice Dialing Yes .Call Timer Yes .Conference Call Capability Yes .Voice Recorder Yes .Caller ID Yes .Speakerphone Yes .Wireless Interface IEEE 802.11g,
IEEE 802.11b,
Bluetooth 2.1 EDR,
IEEE 802.11n .Additional Features Multitasking,
Widgets support .Communicator Features
Operating System Google Android 2.3 .Synchronization With PC Yes .User Memory 16 GB .Messaging & Data Services
Short Messaging Service (SMS) Yes .Messaging Services Google Talk .Mobile Email Yes .Supported Email Protocols SMTP,
POP3,
IMAP4 .GPRS (General Packet Radio Service) Yes .EDGE (Enhanced Data Rates For Global Evolution) Yes .Internet Browser Yes .Included Services YouTube,
Gmail,
Google Search,
Android Market .HSDPA (High Speed Downlink Packet Access) Yes .Messaging / Data Features Text messages,
Multimedia messages (MMS),
E-Mail .Digital Camera
Camera highlights With a resolution of 5 megapixels, this camera phone will give you better pictures than other phones. .Sensor Resolution 5 megapixels .Still Image Resolutions 2560 x 1920 .Focus Adjustment Automatic .White Balance Automatic,
Presets .Camera Light Source Flash .Video Recorder Resolutions 720 x 480 .Digital Video Formats H.264,
H.263,
MPEG-4 .Features Video recording,
Geo-tagging .GPS System
Included GPS Software Google Maps .Organizer
Alarm Clock Yes .Calendar Yes .Reminder Yes .Display
Type OLED display .Technology Super AMOLED .Display Resolution 800 x 480 pixels .Diagonal Size 4 in .Color Support Color .Features Wallpaper .Digital Player (Recorder)
Supported Digital Audio Standards M4A,
MP3,
MIDI,
Ogg Vorbis,
AAC,
AMR .Connections
Connector Type 1 x Micro-USB,
1 x Headset jack - Mini-phone 3.5 mm .Miscellaneous
Resistance Fingerprint-resistant oleophobic coating .Specific absorption rate (SAR) 0.9 W/Kg .Power
Type Power adapter .Battery
Technology - Lithium ion .Capacity 1500 mAh .Talk Time Up to 840 min (2G),
Up to 402 min (3G) .Standby Time Up to 17.8 days on 3G/ Up to 29.7 days on 2G .

Samsung Nexus S 4G (Sprint):
 $149.99


Phone can Help to Moms in Shopping

Greystripe, the research firm, studied more than 230 women who were using iPhone, iPod Touch or Android devices while making shopping decisions. The study also reported the women preferred free apps more.The new age moms are turning to smartphones for help in shopping. Not that they are shopping from the phones itself, rather they are using the phones to find out where the stores are and also for comparing prices as well, says a research firm Greystripe.
In a press release, the research firm says that close to half of the moms are using these devices to locate stores and 36 per cent of them are comparing prices using the smartphones.
"Smartphones have become the super tool for moms on the go," said Dane Holewinski, director of marketing with Greystripe. "The majority of moms with smartphones are using those devices for their day to day tasks especially shopping, making them the ideal target for advertisers."
Greystripe studied the shopping behaviour of over 230 women who were using iPhone and iPod Touch devices or Android smartrphones for help in making their shopping decisions. The women participated in the survey through mobile banner ads placed by Greystripe and 66 per cent of them admitted they took the help of mobile phones while making their shopping decisions. The study also reported 57 per cent women used coupons to get discounts on their shopping every time.
The research also found women were more responsive to mobile advertising, and about 91 per cent respondents said they preferred free apps with advertisements.
Greystripe itself is a mobile ad network, so it does have an interest in the results of the survey.

how to use a color in horizontal progress bar ?

Create a one folder name as Drawable and create another xml in that folder
res/drawable/myprogressbar.xml

<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
 <item android:id="@android:id/background">
  <shape>
   <corners android:radius="25dip" />
   <gradient android:startColor="#000000" android:endColor="#000000" />
   <stroke android:width="1dp" android:color="#000000" />
  </shape>
 </item>

 <item android:id="@android:id/progress">
  <clip>
   <shape>
    <corners android:radius="35dip" />
    <gradient android:startColor="#990000" android:endColor="#E6E8FA" />
    <!--
     <stroke android:width="1dp" android:color="#6B8E23" />
    -->
   </shape>
  </clip>
 </item>
</layer-list>


this xml files can show the loading progress bar in a color.

main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent" android:orientation="vertical">
    <ProgressBar android:layout_marginLeft="5dp" android:layout_width="250dp" android:progressDrawable="@drawable/myprogressbar" android:id="@+id/progressBar1" android:layout_marginBottom="90dp" android:layout_marginRight="10dp" style="?android:attr/progressBarStyleHorizontal" android:layout_height="wrap_content"></ProgressBar>
</LinearLayout>



Friday, 6 May 2011

How to use ExpandableListView using Check box




how to add checkboxes to an expandable list view like this one? Nothing can be simpler, you just add CheckBox control to the child view that forms the row and that's it. Except that it does not work without some tweaks.

package com.pack;

import android.app.ExpandableListActivity;
import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ListView;
import android.widget.CheckBox;
import android.widget.ExpandableListView;
import android.widget.SimpleExpandableListAdapter;
import android.widget.TextView;
import java.util.List;
import java.util.ArrayList;
import android.util.Log;

public class ELSample extends ExpandableListActivity
{
    private static final String LOG_TAG = "ElistCBox2";
    private ColorAdapter expListAdapter;

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle icicle)
    {
        super.onCreate(icicle);
        setContentView(R.layout.main);
        ArrayList<String> groupNames = new ArrayList<String>();
        groupNames.add( "Food" );
   groupNames.add( "Fruit" );
   groupNames.add( "Juice" );
   groupNames.add( "Ice Cream" );
        ArrayList<ArrayList<Color>> colors = new ArrayList<ArrayList<Color>>(); 
        ArrayList<Color> color = new ArrayList<Color>();
        color.add( new Color( "Meals","Indian Meals", false ) ); 
        color.add( new Color( "Andra Meals","Staple food", false ) );
color.add( new Color( "Sea-Food","Butter fish", true ) ); 
color.add( new Color( "Crispy-Food","Burger", false ) );
        colors.add( color );
        
        color = new ArrayList<Color>();
color.add( new Color( "Apple","American apple",false ) );
color.add( new Color(  "Orange","Navel orange",false ) ); 
color.add( new Color( "Grape","Black Grape", true ) );
        colors.add( color );
        color = new ArrayList<Color>();
color.add( new Color( "Milk Shake","Butter Fruit Mix",true ) );
color.add( new Color( "Carrot","Juice with cherry",false ) ); 
color.add( new Color( "Mango","Juice with curd", true ) );
        colors.add( color );
        color = new ArrayList<Color>();
color.add( new Color( "Strawberry","Cone",true ) );
color.add( new Color( "Brain Freeze Ice Cream","Bar",false ) ); 
color.add( new Color( "Cookie Puss Ice Cream","Chocolate Flavour", false ) );
        colors.add( color );

expListAdapter = new ColorAdapter( this,groupNames, colors );
setListAdapter( expListAdapter );
    }

    public void onContentChanged  () {
        super.onContentChanged();
        Log.d( LOG_TAG, "onContentChanged" );
    }

    public boolean onChildClick(
            ExpandableListView parent, 
            View v, 
            int groupPosition,
            int childPosition,
            long id) {
        Log.d( LOG_TAG, "onChildClick: "+childPosition );
        CheckBox cb = (CheckBox)v.findViewById( R.id.check1 );
        if( cb != null )
            cb.toggle();
        return false;
    }
}

_________________________________________________________________________________

The first bizarre thing you can notice in res/layout/child_row.xml that the CheckBox is made non-focusable. Why to do that when we want the checkbox to capture "click" events beside "touch" events? There is a complicated answer already presented in this post. The ViewGroup encapsulating the list row (the LinearLayout in res/layout/child_row.xml) must retain the focus otherwise we don't get onChildClick events (see ElistCBox.java).



public class ColorAdapter extends BaseExpandableListAdapter {

    private Context context;
    private ArrayList<String> groups;
    private ArrayList<ArrayList<Color>> colors;
    private LayoutInflater inflater;

    public ColorAdapter(Context context, 
                        ArrayList<String> groups,
ArrayList<ArrayList<Color>> colors ) { 
        this.context = context;
this.groups = groups;
        this.colors = colors;
        inflater = LayoutInflater.from( context );
    }

    public Object getChild(int groupPosition, int childPosition) {
        return colors.get( groupPosition ).get( childPosition );
    }

    public long getChildId(int groupPosition, int childPosition) {
        return (long)( groupPosition*1024+childPosition );  // Max 1024 children per group
    }

    public View getChildView(int groupPosition, int childPosition, boolean isLastChild, View convertView, ViewGroup parent) {
        View v = null;
        if( convertView != null )
            v = convertView;
        else
            v = inflater.inflate(R.layout.child_row, parent, false); 
        Color c = (Color)getChild( groupPosition, childPosition );
TextView color = (TextView)v.findViewById( R.id.childname );
if( color != null )
color.setText( c.getColor() );
TextView rgb = (TextView)v.findViewById( R.id.rgb );
if( rgb != null )
rgb.setText( c.getRgb() );
CheckBox cb = (CheckBox)v.findViewById( R.id.check1 );
        cb.setChecked( c.getState() );
        return v;
    }

    public int getChildrenCount(int groupPosition) {
        return colors.get( groupPosition ).size();
    }

    public Object getGroup(int groupPosition) {
        return groups.get( groupPosition );        
    }

    public int getGroupCount() {
        return groups.size();
    }

    public long getGroupId(int groupPosition) {
        return (long)( groupPosition*1024 );  // To be consistent with getChildId
    } 

    public View getGroupView(int groupPosition, boolean isExpanded, View convertView, ViewGroup parent) {
        View v = null;
        if( convertView != null )
            v = convertView;
        else
            v = inflater.inflate(R.layout.group_row, parent, false); 
        String gt = (String)getGroup( groupPosition );
TextView colorGroup = (TextView)v.findViewById( R.id.childname );
if( gt != null )
colorGroup.setText( gt );
        return v;
    }

    public boolean hasStableIds() {
        return true;
    }

    public boolean isChildSelectable(int groupPosition, int childPosition) {
        return true;
    } 

    public void onGroupCollapsed (int groupPosition) {} 
    public void onGroupExpanded(int groupPosition) {}


}


Then Create another class for set a color,name as Color.java

public class Color {
    public String color = null;
    public String rgb = null;
    public boolean state = false;

    public Color( String color, String rgb, boolean state ) {
        this.color = color;
        this.rgb = rgb;
        this.state = state;
    }

    public String getColor() {
   return color;
    }

    public String getRgb() {
   return rgb;
    }

    public boolean getState() {
   return state;
    }

}
_________________________________________________________________________________

This would solve the problem for a Button but not for a CheckBox. Actually, I don't know why the Button behaves correctly and the CheckBox does not. My experience is that even if CheckBox has the focus, clicking on the row of the CheckBox does not toggle its state. I am curious if anyone can provide an explanation, here I just record the fact. Remove the android:focusable="false" line from the CheckBox element in child_row.xml and observe, that you can click on the highlighted row as much as you like but the CheckBox does not toggle. That's why I implemented it by "hand" - I took away the focus from the CheckBox, this makes the child row deliver onChildClick events then I toggled the state of the CheckBox programmatically. If anyone has a better solution, I would be deeply interested.

[Name as Group_row.xml]

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="horizontal"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content">

    <TextView android:id="@+id/childname"
         android:paddingLeft="50px"
         android:textSize="14px"
          android:textColor="#990000"
         android:textStyle="italic"
         android:layout_width="150px"
         android:layout_height="wrap_content"/>

</LinearLayout>

[close group_row.xml]

Then again create a new child xml file,name as Child_row.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="horizontal"
    android:layout_width="fill_parent"
    android:background="#3300FF"
    android:layout_height="wrap_content">

    <TextView android:id="@+id/childname"
         android:paddingLeft="50px"
         android:focusable="false"
         android:textSize="14px"
         android:textStyle="italic"
         android:layout_width="150px"
         android:layout_height="wrap_content"/>

    <TextView android:id="@+id/rgb"
         android:focusable="false"
         android:textSize="14px"
         android:textStyle="italic"
         android:layout_width="100px"
         android:layout_height="wrap_content"/>

    <CheckBox android:id="@+id/check1"
           android:focusable="false"
           android:layout_width="wrap_content"
           android:layout_height="wrap_content"/>

</LinearLayout>