ViewSwitcher.ViewFactory makeView()方法的编程方法

时间:2012-01-24 00:54:25

标签: java android

我一直在尝试创建一个简单的类来实现ViewSwitcher.ViewFactory接口,该接口基于“Sams在24小时内自学Android应用程序开发”中开发的项目。在示例中,makeView()方法使布局膨胀以获取视图。但是,我想以编程方式执行它并且它不起作用。

活动的onCreate()方法如下所示:

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");
}

建议的解决方案是这样的:

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;
    }
}

资源文件是:

<?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>

虽然我想这样:

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;
    }
}

当我使用inflate方法但没有以编程方式执行时,我显示“blablabla”文本。你能指出我的代码中的错误吗?

2 个答案:

答案 0 :(得分:2)

mQuestionText = (TextSwitcher) findViewById(R.id.MyTextSwitcher);

您正在通过ID MyTextSwitcher找到该视图。如果您以编程方式创建视图,请确保设置该ID。

view.setId(R.id.MyTextSwitcher);

<强>更新

糟糕,没有仔细阅读你的代码。你是对的,因为你从XML中膨胀,你的ID应该已经正确设置了。您可能缺少的实际上是将视图添加到视图层次结构中。您需要找到一个父ViewGroup(例如LinearLayout或'RelativeLayout , etc.) under which you want to put MyTextSwitcher , let's call it root`,并添加如下内容:

root.addView(view);

答案 1 :(得分:0)

我发现我提供的代码有什么问题。这是错误的,因为它将资源的ID作为函数参数而不是值本身。

textView.setTextColor(R.color.title_color);
textView.setTextSize(R.dimen.game_question_size);

这是正确的:

textView.setTextColor(getApplicationContext().getResources().getColor(R.color.title_color));
textView.setTextSize(TypedValue.COMPLEX_UNIT_PX, getApplicationContext().getResources().getDimension(R.dimen.game_question_size));