Domanda

I have two TextViews in a layout using a row layout for a SimpleCursorAdapter. The TextViews have their values populated from the SimpleCursorAdapter.

The first view displays the name of a computer host, that's fine but the second displays the mac address of the host, at current in the database I've got I'm storing it as a string in Hex format.

What I want to do is not have the formatting for the mac address in the database but format it programatically using a custom TextView or other else that will work. So basically AABBCCEEFF00 will become AA:BB:CC:EE:FF:00 when the SimpleCursorAdapter populates that TextView extened class.

What's the best way forward with this and where should I plug in the code if I do use custom TextView?

I've also seen reference to View Binding? but unsure if that's the route to go, I'm very much about making code modular and rather not override complex code when extending a simple class is possible.

È stato utile?

Soluzione 2

Turns out the best ways was with a ViewBinder setup, I followed this answer in the end.

Android, using SimpleCursorAdapter to set colour not just strings

Once I knew this I also changed the column to be a Blob instead of VarChar to make it a bit nicer as well.

    SimpleCursorAdapter.ViewBinder binder = new SimpleCursorAdapter.ViewBinder() {
        @Override
        public boolean setViewValue(View view, Cursor cursor, int columnIndex) {
            String name = cursor.getColumnName(columnIndex);
            if ("mac_address".equals(name)) {
                byte[] macAddress = cursor.getBlob(columnIndex);
                TextView textView = (TextView)view;
                textView.setText(Target.getMacAddress(macAddress));
                return true;
            }
            return false;
        }
    };

Altri suggerimenti

As far as I could understand your question,You want to convert AABBCCDDEEFF into AA:BB:CC:DD:EE:FF programmatically.let me know if I didn't get your question.

look at following code, from here,you are going to call a function to get formatted mac

String formattedMac = new String();
formattedMac=getFormattedMac("AABBCCDDEEFF");
Log.e("formatted Mac", formattedMac);//it will be look like, AA:BB:CC:DD:EE:FF

and here is the function returning formatted mac,

    private String getFormattedMac(String mac) {
    String result = new String();
    result="";
    int start=0;
    int end=2;
    int max=mac.length()+2;

    while(end<max)
    {
        result = result+mac.substring(start, end);
        if(end<mac.length())
        {
            result = result+":";
        }
        Log.e("result", result);
        start=start+2;
        end=end+2;
    }

    return result;
}
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top