I’ve been trying to create a simple class that implements the ViewSwitcher.ViewFactory interface basing on the project developed in “Sams Teach Yourself Android Application Development in 24 Hours”. In the example the makeView() method inflates a layout in order to obtain a View. However, I wanted to do it programmatically and it didn’t work.
The onCreate() method of the activity looks like this:
private TextSwitcher mQuestionText;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.game);
mQuestionText = (TextSwitcher) findViewById(R.id.MyTextSwitcher);
mQuestionText.setFactory(new MyTextSwitcherFactory());
mQuestionText.setCurrentText("blablabla");
}
The proposed solution goes like this:
private class MyTextSwitcherFactory implements ViewSwitcher.ViewFactory {
public View makeView() {
TextView textView = (TextView) LayoutInflater.from(
getApplicationContext()).inflate(
R.layout.text_switcher_view,
mQuestionText, false);
return textView;
}
}
The resource file is:
<?xml version="1.0" encoding="utf-8"?>
<TextView
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:textColor="@color/title_color"
android:textSize="@dimen/game_question_size"
android:gravity="center"
android:text="Testing String"
android:layout_height="match_parent"
android:padding="10dp">
</TextView>
While I wanted to it like this:
private class MyImageSwitcherFactory implements ViewSwitcher.ViewFactory {
public View makeView() {
TextView textView = new TextView(getApplicationContext());
textView.setLayoutParams(new TextSwitcher.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT));
textView.setTextColor(R.color.title_color);
textView.setTextSize(R.dimen.game_question_size);
textView.setGravity(Gravity.CENTER);
textView.setText("Test");
return textView;
}
}
I get the “blablabla” text displayed when I use the inflate method but not doing it programmatically. Could you point to an error in my code, please?
I found out what was wrong with the code I provided. This is wrong since it gives the ID of the resource as the function parameter instead of the value itself.
This is correct: