Tuesday 10 January 2012

Number Puzzle

The Below program is the Splash Screen, After finishing the splash screen activity, the options page will be displayed.


package com.dynamic.layout;

import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.util.Log;

public class Splash_Screen extends Activity
{
    public static final String PREFS_NAME = "ScorePrefs";
    static SharedPreferences settings;
    SharedPreferences.Editor editor;
   
    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.splash_screen);
       
        new CountDownTimer(5000,1000){

            @Override
            public void onFinish()
            {
                // TODO Auto-generated method stub
                finish();
                Intent ingridmenu=new Intent(Splash_Screen.this,OptionLayout.class);
                startActivity(ingridmenu);
            }

            @Override
            public void onTick(long millisUntilFinished)
            {
                Log.d("Timer Coundown", Long.toString(millisUntilFinished));
                // TODO Auto-generated method stub
               
            }
           
        }.start();
    }
}


The Below Program is the Option page Activity.

package com.dynamic.layout;

import java.util.ArrayList;

import android.app.Activity;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.util.Log;
import android.view.Display;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;

public class OptionLayout extends Activity
{
    DBRecordHandler recHandler=null;
   
    Button start_btn=null;
    Button scores_btn=null;
    Button exit_btn=null;
   
    static int screenWidth=0,screenHeight=0;
   
    public static ArrayList<MoveListValues> scoreList=new ArrayList<MoveListValues>();
   
    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.options_layout);
       
        Display display = getWindowManager().getDefaultDisplay();
        screenWidth = display.getWidth();
        screenHeight = display.getHeight();
        Log.d("screenWidth",Integer.toString(screenWidth));
        Log.d("Screen Height",Integer.toString(screenHeight));
       
        start_btn=(Button)findViewById(R.id.start_btn);
        scores_btn=(Button)findViewById(R.id.scores_btn);
        exit_btn=(Button) findViewById(R.id.exit_btn);
       
        getScoreRecords();
       
        start_btn.setOnClickListener(new OnClickListener(){

            @Override
            public void onClick(View v)
            {
                // TODO Auto-generated method stub
                Intent instart=new Intent(OptionLayout.this, DynamicLayout.class);
                startActivity(instart);
            }
           
        });
       
        scores_btn.setOnClickListener(new OnClickListener(){

            @Override
            public void onClick(View v)
            {
                // TODO Auto-generated method stub
                Intent inscore=new Intent(OptionLayout.this, ScoreList.class);
                startActivity(inscore);
            }
           
        });
       
        exit_btn.setOnClickListener(new OnClickListener(){

            @Override
            public void onClick(View v)
            {
                // TODO Auto-generated method stub
                finish();
            }
           
        });
    }
   
    public void getScoreRecords()
    {
        scoreList.clear();
       
        recHandler=new DBRecordHandler(OptionLayout.this);
        recHandler.open();
       
        Cursor cur=recHandler.getAllUser();
        startManagingCursor(cur);
        cur.moveToFirst();
        if(cur.getCount()>0)
        {
            while(cur.isAfterLast()==false)
            {   
                //Log.v("OptionLayout", "Name========>>>"+cur.getString(cur.getColumnIndex(DBRecordHandler.USERNAME)));
                //Log.v("OptionLayout", "Moves========>>>"+cur.getString(cur.getColumnIndex(DBRecordHandler.MOVES)));
                //Log.v("OptionLayout", "Time========>>>"+cur.getString(cur.getColumnIndex(DBRecordHandler.TIME)));
               
                String name=cur.getString(cur.getColumnIndex(DBRecordHandler.USERNAME));
                String moves=cur.getString(cur.getColumnIndex(DBRecordHandler.MOVES));
                String time=cur.getString(cur.getColumnIndex(DBRecordHandler.TIME));
               
                scoreList.add(new MoveListValues(name, moves, time));
               
                cur.moveToNext();
            }
        }
       
        else
        {
            Toast.makeText(OptionLayout.this, "No Scores Details", Toast.LENGTH_SHORT).show();
        }
        recHandler.close();
    }
   
    public void onResume()
    {
        super.onResume();
        Log.v("OptionLayout", "=========== Calling OnResume ============");
        getScoreRecords();
    }
}

Below is the Layout that are used in the Option activity.

<?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"
  android:gravity="center"
  android:background="#112C4F">
 
  <Button android:id="@+id/start_btn"
      android:layout_width="fill_parent"
      android:layout_height="50dp"
      android:layout_marginLeft="20dp"
      android:layout_marginRight="20dp"
      android:text="Start"
      android:textColor="#FFFFFF"
      android:textStyle="bold"
      android:textSize="18sp"
      android:background="@drawable/shuffle_button_selector">
  </Button>
 
   <Button android:id="@+id/scores_btn"
      android:layout_width="fill_parent"
      android:layout_height="50dp"
      android:layout_marginLeft="20dp"
      android:layout_marginRight="20dp"
      android:layout_marginTop="10dp"
      android:text="Scores"
      android:textColor="#FFFFFF"
      android:textStyle="bold"
      android:textSize="18sp"
      android:background="@drawable/shuffle_button_selector">
  </Button>
 
   <Button android:id="@+id/exit_btn"
      android:layout_width="fill_parent"
      android:layout_height="50dp"
      android:layout_marginLeft="20dp"
      android:layout_marginRight="20dp"
      android:layout_marginTop="10dp"
      android:text="Exit"
      android:textColor="#FFFFFF"
      android:textStyle="bold"
      android:textSize="18sp"
      android:background="@drawable/shuffle_button_selector">
  </Button>
 
</LinearLayout>


Three buttons are used in the option page, first one is start to start the puzzle, second is scores to list the highscores in the puzzle and third one is exit to close the application.


OnClicking the start button, the puzzle activity will be started.

Below is the program for creating the view of the puzzle.

package com.dynamic.layout;

import java.util.ArrayList;
import java.util.Collections;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.graphics.Color;
import android.os.Bundle;
import android.os.SystemClock;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup.LayoutParams;
import android.widget.Button;
import android.widget.Chronometer;
import android.widget.EditText;
import android.widget.TableLayout;
import android.widget.TableRow;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.Chronometer.OnChronometerTickListener;

public class DynamicLayout extends Activity implements OnClickListener
{
    public static final int LEFT_MOVE=1;
    public static final int RIGHT_MOVE=2;
    public static final int TOP_MOVE=3;
    public static final int BOTTOM_MOVE=4;
   
    TableLayout tableLayout=null;
    Button shuffle_btn=null;
    TextView moves=null;
    TextView least_moves=null;
    Chronometer time_count=null;
   
    DBRecordHandler recHandler=null;
   
    int value=0, move_count=0;
    String currentTime;
    long elapsedTime = 0;
   
    public ArrayList<String> numbers=new ArrayList<String>();
    public ArrayList<String> real_numbers=new ArrayList<String>();
    public String[][] num_array=new String[4][4];
    ArrayList<MoveListValues> nearest_list=new ArrayList<MoveListValues>();
   
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
       
        tableLayout=(TableLayout)findViewById(R.id.table_layout);
        shuffle_btn=(Button)findViewById(R.id.shuffle_btn);
        moves=(TextView)findViewById(R.id.moves_count);
        least_moves=(TextView)findViewById(R.id.least_moves);
        time_count=(Chronometer)findViewById(R.id.timer_count);
       
        try
        {
            if(OptionLayout.scoreList.size()<1)
            {
                least_moves.setText("Least Move : 0");
            }
           
            else
            {
                least_moves.setText("Least Move : "+OptionLayout.scoreList.get(0).moves.trim());
            }
        }
        catch(Exception e)
        {
           
        }
       
       
       
        for(int i=1; i<16; i++)
        {
            real_numbers.add(Integer.toString(i));
        }
        real_numbers.add("");
       
        storeNumberList();
        shuffle();
       
        //time_count.start();
       
        shuffle_btn.setOnClickListener(new OnClickListener(){

            @Override
            public void onClick(View v)
            {
                // TODO Auto-generated method stub
                storeNumberList();
                shuffle();
            }
        });
       
        time_count.setOnChronometerTickListener(new OnChronometerTickListener(){

            @Override
            public void onChronometerTick(Chronometer chronometer)
            {
                // TODO Auto-generated method stub
                long minutes = ((SystemClock.elapsedRealtime() - time_count.getBase()) / 1000) / 60;
                long seconds = ((SystemClock.elapsedRealtime() - time_count.getBase()) / 1000) % 60;
               
                String min=Long.toString(minutes);
                String sec=Long.toString(seconds);
               
                if(sec.length()<2)
                {
                    sec="0"+sec;
                }
                currentTime = min + ":" + sec;
                //Log.v("DynamicLayout", "Current Time=====>>>"+currentTime);
               
                chronometer.setText("Time : "+currentTime);
                //elapsedTime = SystemClock.elapsedRealtime();
            }
           
        });
    }
   
    public void storeNumberList()
    {
        numbers.clear();
        for(int i=1; i<16; i++)
        {
            numbers.add(Integer.toString(i));
        }
        numbers.add("");
    }
   
    public void shuffle()
    {
        //Collections.shuffle(numbers);
       
        move_count=0;
        moves.setText("Moves = "+move_count);
       
        time_count.setBase(SystemClock.elapsedRealtime());
        time_count.start();
       
        displayShuffledRows();
    }

    public void displayShuffledRows()
    {
        // TODO Auto-generated method stub
        tableLayout.removeAllViews();
        value=0;
        int ei=-1,ej=-1;
       
        for(int i=0; i<4; i++)
        {
            TableRow tableRow=new TableRow(this);
            tableRow.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
            tableRow.setGravity(Gravity.CENTER_HORIZONTAL);
            for(int j=0; j<4; j++)
            {
                Button button=new Button(this);
               
                button.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
               
                num_array[i][j]=numbers.get(value);
               
                if(numbers.get(value).equals(""))
                {
                    ei=i;
                    ej=j;
                }
               
                button.setText(""+numbers.get(value));
                button.setTextSize(25.0f);
                button.setBackgroundResource(R.drawable.number_buttons_selector);
                button.setTextColor(Color.WHITE);
                button.setOnClickListener(this);
               
                value++;
               
                if(OptionLayout.screenWidth==540)
                {
                    tableRow.addView(button,120,120);
                }
                else
                {
                    tableRow.addView(button,60,60);
                }
               
               
            }
           
            tableLayout.addView(tableRow);
        }
       
        getNearestValues(ei,ej);
    }
   
    public void getNearestValues(int i, int j)
    {
        nearest_list.clear();
       
        //Log.v("Dynamic Layout", "Empty Position=============>>>"+i+","+j);
       
        if(i==0 && j==0)
        {
            nearest_list.add(new MoveListValues(num_array[i][j+1], RIGHT_MOVE, i, j+1, i, j));
            nearest_list.add(new MoveListValues(num_array[i+1][j], BOTTOM_MOVE, i+1, j, i, j));
        }
        else if(i==0 && (j==1 || j==2))
        {
            nearest_list.add(new MoveListValues(num_array[i][j-1], LEFT_MOVE, i, j-1, i, j));
            nearest_list.add(new MoveListValues(num_array[i][j+1], RIGHT_MOVE, i, j+1, i, j));           
            nearest_list.add(new MoveListValues(num_array[i+1][j], BOTTOM_MOVE, i+1, j, i, j));
        }       
        else if(i==0 && j==3)
        {
            nearest_list.add(new MoveListValues(num_array[i][j-1], LEFT_MOVE, i, j-1, i, j));
            nearest_list.add(new MoveListValues(num_array[i+1][j], BOTTOM_MOVE, i+1, j, i, j));
        }       
        else if((i==1 || i==2) && j==0)
        {
            nearest_list.add(new MoveListValues(num_array[i][j+1], RIGHT_MOVE, i, j+1, i, j));
            nearest_list.add(new MoveListValues(num_array[i-1][j], TOP_MOVE, i-1, j, i, j));
            nearest_list.add(new MoveListValues(num_array[i+1][j], BOTTOM_MOVE, i+1, j, i, j));
        }
        else if((i==1 || i==2) && (j==1 || j==2))
        {
            nearest_list.add(new MoveListValues(num_array[i][j-1], LEFT_MOVE, i, j-1, i, j));
            nearest_list.add(new MoveListValues(num_array[i][j+1], RIGHT_MOVE, i, j+1, i, j));
            nearest_list.add(new MoveListValues(num_array[i-1][j], TOP_MOVE, i-1, j, i, j));
            nearest_list.add(new MoveListValues(num_array[i+1][j], BOTTOM_MOVE, i+1, j, i, j));
        }       
        else if((i==1 || i==2) && j==3)
        {
            nearest_list.add(new MoveListValues(num_array[i][j-1], LEFT_MOVE, i, j-1, i, j));
            nearest_list.add(new MoveListValues(num_array[i-1][j], TOP_MOVE, i-1, j, i, j));
            nearest_list.add(new MoveListValues(num_array[i+1][j], BOTTOM_MOVE, i+1, j, i, j));
        }       
        else if(i==3 && j==0)
        {
            nearest_list.add(new MoveListValues(num_array[i][j+1], RIGHT_MOVE, i, j+1, i, j));
            nearest_list.add(new MoveListValues(num_array[i-1][j], TOP_MOVE, i-1, j, i, j));
        }
        else if(i==3 && (j==1 || j==2))
        {
            nearest_list.add(new MoveListValues(num_array[i][j-1], LEFT_MOVE, i, j-1, i, j));
            nearest_list.add(new MoveListValues(num_array[i][j+1], RIGHT_MOVE, i, j+1, i, j));
            nearest_list.add(new MoveListValues(num_array[i-1][j], TOP_MOVE, i-1, j, i, j));
        }       
        else if(i==3 && j==3)
        {
            nearest_list.add(new MoveListValues(num_array[i][j-1], LEFT_MOVE, i, j-1, i, j));
            nearest_list.add(new MoveListValues(num_array[i-1][j], TOP_MOVE, i-1, j, i, j));
        }
        else
        {
            Toast.makeText(DynamicLayout.this, "I and J value are Negative", Toast.LENGTH_SHORT).show();
        }   
    }

    @Override
    public void onClick(View v)
    {
        // TODO Auto-generated method stub
        String text=((Button) v).getText().toString();
       
        numbers.clear();
       
        for(int i=0; i<nearest_list.size(); i++)
        {
            if(text.equalsIgnoreCase(nearest_list.get(i).number.trim()))
            {
                move_count++;
                //Log.v("DynamicLayout", "Direction==========>>>"+nearest_list.get(i).direction);
                int empty_i=nearest_list.get(i).empty_i;
                int empty_j=nearest_list.get(i).empty_j;
               
                int move_i=nearest_list.get(i).move_i;
                int move_j=nearest_list.get(i).move_j;
               
                String temp=num_array[move_i][move_j];
                num_array[move_i][move_j]="";
                num_array[empty_i][empty_j]=temp;
            }
        }
       
        for(int i=0; i<4; i++)
        {
            for(int j=0; j<4; j++)
            {
                //Log.v("Printing Num Array", "After Values======("+i+","+j+")=========>>>"+num_array[i][j]);
                numbers.add(num_array[i][j]);
            }
        }
        moves.setText("Moves = "+move_count);
        displayShuffledRows();
        int i=0;
        comparition(i);
    }
   
    public void comparition(int i)
    {
        if(i<real_numbers.size())
        {
            //System.out.println("List 1 value=====>>>"+real_numbers.get(i) + " List 2 Value=====>>>"+numbers.get(i));
            if(real_numbers.get(i).equals(numbers.get(i)))
            {
                //System.out.println("Comparition Progress.....");
                i++;
                if(i==real_numbers.size())
                {
                    //System.out.println("Solution Obtained.....");
                    time_count.stop();
                    showAlert(DynamicLayout.this, "Solution Obtained in "+move_count+" Moves and Time is "+currentTime);
                }
                else
                {
                    comparition(i);
                }
            }
            else
            {
                //System.out.println("Solution Not Obtained.....");
            }
        }
    }
   
    public void insertRecord(String name)
    {
        recHandler=new DBRecordHandler(DynamicLayout.this);
        recHandler.open();
        long res=recHandler.insertRecord(name, move_count, currentTime);
        Log.v("Record Inserted========>>>", Long.toString(res));
        recHandler.close();
    }
   
    public void showAlert(Context context, String desc)
    {
       
        final AlertDialog alert=new AlertDialog.Builder(context).create();

        alert.setTitle("Congratulation");
        alert.setMessage(desc);
        alert.setIcon(R.drawable.smile_emotion);

        // Set an EditText view to get user input
        final EditText input = new EditText(this);
        input.setHint("Name");
        alert.setView(input);

        alert.setButton("Ok", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int whichButton)
            {
              String value = input.getText().toString();
              insertRecord(value);
              shuffle();
              alert.dismiss();
            }
        });


        alert.show();
    }
}


Below is the layout that are used in the puzzle view. Layout name is 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"
    android:gravity="center"
    android:background="#112C4F">
   
    <RelativeLayout android:id="@+id/timer_count_rellayout"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content">
       
        <TextView android:id="@+id/least_moves"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentRight="true"
            android:layout_marginRight="10dp"
            android:layout_marginBottom="5dp"
            android:text="Least Moves"
            android:textStyle="bold"
            android:textSize="15sp"
            android:textColor="#FFFFFF">
        </TextView>
       
        <Chronometer android:id="@+id/timer_count"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_below="@+id/least_moves"
            android:format="0:00"   
            android:textColor="#FFFFFF"
            android:layout_alignParentLeft="true"
            android:layout_marginLeft="10dp">
        </Chronometer>
       
        <TextView android:id="@+id/moves_count"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentRight="true"
            android:layout_marginRight="10dp"
            android:layout_below="@+id/least_moves"
            android:text="Moves"
            android:textStyle="bold"
            android:textSize="15sp"
            android:textColor="#FFFFFF">
        </TextView>
       
    </RelativeLayout>
   
   
   
    <TableLayout android:id="@+id/table_layout"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="20dp"
        android:gravity="center">
    </TableLayout>
   
    <Button android:id="@+id/shuffle_btn"
        android:layout_width="100dp"
        android:layout_height="50dp"
        android:layout_marginTop="10dp"
        android:background="@drawable/shuffle_button_selector"
        android:text="Shuffle"
        android:textColor="#FFFFFF">
    </Button>

</LinearLayout>


Text view for Displaying the least moves.
Chronometer for running the time.
Text view for Displaying the moves count.
Table Layout for displaying the puzzle numbers.
Button for suffle the puzzle numbers.

OnClicking the suffle button, the puzzle will be restarted, timer will also be restarted.

Sqlite database will be used for maintaining the scores details.

The following two class is used for creating the database and managing records in the database

package com.dynamic.layout;

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.database.sqlite.SQLiteDatabase.CursorFactory;
import android.util.Log;

public class DataBaseHandler extends SQLiteOpenHelper
{
   
    public static String DataBase_Create="create table movecountdb(_id integer primary key autoincrement,"
        +"username text not null, moves integer not null, time text not null);";

    public DataBaseHandler(Context context, String name, CursorFactory factory,int version)
    {
        super(context, name, null, version);
        // TODO Auto-generated constructor stub
    }

    @Override
    public void onCreate(SQLiteDatabase db)
    {
        // TODO Auto-generated method stub
        System.out.println("******** Table Created ***********");
        db.execSQL(DataBase_Create);
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion)
    {
        // TODO Auto-generated method stub
        Log.w(DataBaseHandler.class.getName(), "Upgraded Database From "+oldVersion+" to "+newVersion+" Which Will Destroy All old Data");
        db.execSQL("Drop table if exist userdetails");
        onCreate(db);
    }

}


For Managing Records, the following class is used.

package com.dynamic.layout;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.util.Log;

public class DBRecordHandler
{
    public static String USERNAME="username";
    public static String MOVES="moves";
    public static String TIME="time";
    public static String ROW_ID="_id";
   
    public SQLiteDatabase database;
    public DataBaseHandler dbhandler;
   
    public static String DataBase_Name="movesdetails";
    public static int Database_version=2;
    public static String Table_Name="movecountdb";
    public Context context=null;
   
    public DBRecordHandler(Context context)
    {
        this.context=context;
        dbhandler=new DataBaseHandler(context,DataBase_Name,null,Database_version);
        database=dbhandler.getWritableDatabase();             
    }
   
    public DBRecordHandler open()
    {
        dbhandler=new DataBaseHandler(context,DataBase_Name,null,Database_version);
        database=dbhandler.getWritableDatabase(); 
        return this;
    }
   
    public void close()
    {
        dbhandler.close();
    }
   
    public long insertRecord(String username,int moves,String time)
    {
        ContentValues conval=addDetails(username, moves, time);
        long res=database.insert(Table_Name, null, conval);
        return res;
    }
   
    /*public int updateRecord(long row_id, String username, String password, String email)
    {
        ContentValues updateValues=addDetails(username, password, email);
        int res=database.update(Table_Name, updateValues, ROW_ID+"="+row_id, null);
        return res;
    }
   
    public int deleteRecord(long row_id)
    {
        int res=database.delete(Table_Name, ROW_ID+"="+row_id, null);
        return res;
    }*/
   
    public ContentValues addDetails(String username, int moves, String time)
    {
        Log.v("Record Handler", "username==========>>>"+username);
        Log.v("Record Handler", "Moves==========>>>"+moves);
        Log.v("Record Handler", "Time==========>>>"+time);
       
        ContentValues values=new ContentValues();
        values.put(USERNAME, username);
        values.put(MOVES, moves);
        values.put(TIME, time);
        return values;
    }
   
    public Cursor getAllUser()
    {
        Cursor cur=database.query(Table_Name, new String[]{ROW_ID,USERNAME,MOVES,TIME}, null, null, null, null, MOVES+" ASC");
        return cur;
    }

}


On Clicking the score option in the option page, the score activity will be started.

Below is the class for score activity.

package com.dynamic.layout;

import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ListView;
import android.widget.TextView;

public class ScoreList extends Activity
{
    ListView scorelist=null;
   
    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.scores_list);
       
        scorelist=(ListView)findViewById(R.id.score_listview);
        scorelist.setAdapter(new ScoreListAdapter(this));
    }
   
    public class ScoreListAdapter extends BaseAdapter
    {
        Context mycontext=null;
       
        public ScoreListAdapter(Context c)
        {
            mycontext=c;
        }

        @Override
        public int getCount()
        {
            // TODO Auto-generated method stub
            return OptionLayout.scoreList.size();
        }

        @Override
        public Object getItem(int position)
        {
            // TODO Auto-generated method stub
            return position;
        }

        @Override
        public long getItemId(int position)
        {
            // TODO Auto-generated method stub
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent)
        {
            // TODO Auto-generated method stub
            ViewHolder holder=null;
            if(convertView==null)
            {
                LayoutInflater minflater=LayoutInflater.from(mycontext);
                convertView=minflater.inflate(R.layout.score_list_row, null);
                holder=new ViewHolder();
                holder.textname=(TextView)convertView.findViewById(R.id.name_textview);
                holder.textmove=(TextView)convertView.findViewById(R.id.move_textview);
                holder.texttime=(TextView)convertView.findViewById(R.id.time_textview);
               
                convertView.setTag(holder);
            }
            else
            {
                holder=(ViewHolder)convertView.getTag();
            }
           
            holder.textname.setText(OptionLayout.scoreList.get(position).name.trim());
            holder.textmove.setText("Moves : "+OptionLayout.scoreList.get(position).moves.trim());
            holder.texttime.setText("Time = "+OptionLayout.scoreList.get(position).time.trim());
           
            return convertView;
        }
       
        class ViewHolder
        {
             TextView textname;
             TextView textmove;
             TextView texttime;
        }

    }

}


layout used in the score list class is scores_list.xml

Below is the scores_list.xml content.

<?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">
 
  <ListView android:id="@+id/score_listview"
      android:layout_width="fill_parent"
      android:layout_height="wrap_content">
  </ListView>
 
</LinearLayout>


Below is the layout that are inflated in the score list list view. The name of the layout is score_list_row.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
  xmlns:android="http://schemas.android.com/apk/res/android"
  android:layout_width="fill_parent"
  android:layout_height="wrap_content">
 
  <TextView android:id="@+id/name_textview"
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:layout_alignParentLeft="true"
      android:layout_marginLeft="10dp"
      android:layout_marginTop="10dp"
      android:text="Name"
      android:textStyle="bold"
      android:textSize="20sp"
      android:textColor="#FFFFFF">
  </TextView>
 
  <TextView android:id="@+id/move_textview"
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:layout_below="@+id/name_textview"
      android:layout_alignParentLeft="true"
      android:layout_marginLeft="10dp"
      android:layout_marginTop="10dp"
      android:text="Total Moves : 200 "
      android:textStyle="bold"
      android:textSize="15sp"
      android:textColor="#FFFFFF">
  </TextView>
 
  <TextView android:id="@+id/time_textview"
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:layout_below="@+id/name_textview"
      android:layout_alignParentRight="true"
      android:layout_marginRight="10dp"
      android:layout_marginTop="10dp"
      android:text="Time = 0:00"
      android:textStyle="bold"
      android:textSize="15sp"
      android:textColor="#FFFFFF">
  </TextView>
 
</RelativeLayout>

One more class is created called MoveListValues.jave, this class is used for storing the puzzle possible moves and the corresponding numbers and the direction of the move. It also used for storing the score details. This class is used in the ArrayList Type.

package com.dynamic.layout;

public class MoveListValues
{
    public String number;
    public int direction;
    public int move_i, move_j;
    public int empty_i, empty_j;
   
    public String name, moves, time;
   
    public MoveListValues(String number, int direction, int move_i, int move_j, int empty_i, int empty_j)
    {
        this.number=number;
        this.direction=direction;
        this.move_i=move_i;
        this.move_j=move_j;
        this.empty_i=empty_i;
        this.empty_j=empty_j;
    }
   
    public MoveListValues(String name, String moves, String time)
    {
        this.name=name;
        this.moves=moves;
        this.time=time;
    }

}


Below is the sample output screens.




















No comments:

Post a Comment