【问题标题】:Can android-numberpicker be instantiated as a View?android-numberpicker 可以实例化为视图吗?
【发布时间】:2014-07-20 09:53:14
【问题描述】:

android-numberpicker可以用startActivity发起来启动一个Activity:

startActivity(new Intent(MainActivity.this, LightThemeActivity.class));

它可以作为 AlertDialog 的视图启动吗?也就是说,是否可以将其实例化为 View,然后将其作为输入提供给 setView?例如,类似:

AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
View view = ... //instantiate android-numberpicker as a view
builder.setView(view);

...填写的地方。

编辑

AndroidManifest.xml 包含

<activity android:name="com.example.LightThemeActivity"
          android:theme="@style/SampleTheme.Light" />

我认为这一定是相关的,因为删除它意味着 startActivity(new Intent(MainActivity.this, LightThemeActivity.class)) 不起作用。

解决方案

以下代码(在 MainActivity.java 中)将 NumberPicker 初始化为 AlertDialog 的视图:

NumberPicker np = new NumberPicker(MainActivity.this);
np.setMaxValue(20);
np.setMinValue(0);

AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
builder.setView(np);
builder.show();

您的(在 AndroidManifest.xml 中)中还需要以下内容

<activity android:name="example.MainActivity"
          android:theme="@style/SampleTheme">
    <intent-filter>
        <action android:name="android.intent.action.MAIN" />
        <category android:name="android.intent.category.LAUNCHER" />
    </intent-filter>
</activity>

我错过了 android:theme="@style/SampleTheme"

问题

为什么

getActivity().getLayoutInflater().inflate(R.layout.activity_light, null)

产生通货膨胀异常?

回答

鉴于样式问题已修复,以上不再抛出异常。因此,另一种解决方案如下:

AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);

View view = LayoutInflater.from(MainActivity.this).inflate(R.layout.activity_light, null);
NumberPicker numberPicker = (NumberPicker) view.findViewById(R.id.numberPicker);
numberPicker.setMaxValue(20);
numberPicker.setMinValue(0);

builder.setView(view);

参考文献

以下主题似乎相关:

Using SimonVT number picker and unable to inflate xml Custom number picker inside fragment

谢谢

非常感谢njzk2的指导。

【问题讨论】:

  • 是的,它是一个线性布局。
  • 这个问题似乎离题了,因为这是他们本可以尝试做的事情。
  • CaseyB,我试过了。
  • 成功了吗?您遇到了哪些具体问题?
  • 以上代码不完整。我不知道“...”应该是什么。

标签: java android


【解决方案1】:

是的,它是View 的子类。

因为它是View 的子类,所以你可以这样做:

AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
NumberPicker nb = getActivity().getLayoutInflater().inflate(R.layout.activity_light, null);
builder.setView(nb);

【讨论】:

  • 例如View view = getActivity().getLayoutInflater().inflate(R.layout.activity_light, null);导致 InflateException。
  • activity_light.xml 是否存在于您的 layout 文件夹中?
  • 是的,activity_light.xml 在布局文件夹中。此外, startActivity(new Intent(MainActivity.this, LightThemeActivity.class));正确显示 android-numberpicker。
  • 可能是MainActivity.this.getLayoutInflater(),来自代码的其余部分。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-10-22
  • 2012-01-12
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多