Jujumancer Jujumancer - 5 months ago 9
Android Question

Calling a new layout from a class

I was wondering if it's possible to use setContentView on a class? I'm planning to call a new layout once the class is called. So basically, I'm trying to change the view once I detect an nfc tag.

Main_Activity

@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main__screen);
readCard = new ReadCard(this);
enableReaderMode();
}

public void enableReaderMode()
{
Activity activity = this;
NfcAdapter nfc = NfcAdapter.getDefaultAdapter(activity);
if (nfc != null)
{
nfc.enableReaderMode(activity, readCard, READER_FLAGS, null);
}

}


Class

private Main_Screen mainScreen;
private Context context;
public String PINHolder = null;

IsoDep isoDep;
Activity Main_Screen = (Activity) context;
public ReadCard(Main_Screen mainScreen)
{
this.mainScreen = mainScreen;
}
@Override
public void onTagDiscovered(Tag tag)
{


isoDep = IsoDep.get(tag);

if (isoDep != null)
{
beepSound.start();
try
{
isoDep.connect();
mainScreen.setContentView(R.layout.pin_login);
} catch (IOException e)
{
e.printStackTrace();
}
}
}

Answer

You can't do what you want that way, because only the Activity is "authorized" to modify its contents and children Views. You also can't touch the UI Thread from a background one.

There are some ways you can achieve what you want, I'll try to list some:

For more info on how you can communicate with the UI thread (in this case, with your Activity), check the Android training guide.

Comments