Monday, September 8, 2014

Display ASCII character on ListView

It's a simple example to display ASCII code and character on ListView.


package com.example.androidlistascii;

import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.widget.ArrayAdapter;
import android.widget.ListView;

public class MainActivity extends ActionBarActivity {

 ListView listAscii;
 AsciiCode Asciis[];
 ArrayAdapter<AsciiCode> asciiArrayAdapter;

 @Override
 protected void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.activity_main);
  listAscii = (ListView) findViewById(R.id.asciilist);
  initAsciis();

  asciiArrayAdapter = new ArrayAdapter<AsciiCode>(this,
    android.R.layout.simple_list_item_1, android.R.id.text1, Asciis);
  listAscii.setAdapter(asciiArrayAdapter);
 }

 private void initAsciis() {
  Asciis = new AsciiCode[128];
  for (int i = 0; i < 128; i++) {
   Asciis[i] = new AsciiCode(i);
  }
 }
 
 class AsciiCode{
  int id;
  char charAscii;
  
  AsciiCode(int id){
   this.id = id;
   charAscii = (char)id;
  }
  
  public String toString(){
   return 
    String.format("%03d", id)
    + " /(hex) 0x" + String.format("%02x", id).toUpperCase()
    + " : " + charAscii;
  }
 }
}

<LinearLayout 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:orientation="vertical"
    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.androidlistascii.MainActivity" >

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center_horizontal"
        android:autoLink="web"
        android:text="http://android-er.blogspot.com/"
        android:textStyle="bold" />

    <ListView
        android:id="@+id/asciilist"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />

</LinearLayout>

No comments:

Post a Comment