首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >在Android片段中使用Proteus,但在抛出膨胀器- Proteus Android布局引擎时出现了错误。

在Android片段中使用Proteus,但在抛出膨胀器- Proteus Android布局引擎时出现了错误。
EN

Stack Overflow用户
提问于 2017-12-18 09:56:55
回答 1查看 705关注 0票数 0

请检查我的代码:

代码语言:javascript
复制
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    JSONObject jsonlayout = null ;
    try {
        jsonlayout = new JSONObject(loadJSONFromAsset(getContext()));
    } catch (JSONException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
    ProteusLayoutInflater layoutInflater = (ProteusLayoutInflater)inflater;
    ProteusView view = layoutInflater.inflate(jsonlayout.toString(), null, container, 0);
    return view.getAsView();
}

我希望使用Proteus库来创建视图并将其呈现为片段。

你能告诉我我做错了什么吗?通过这段代码,我得到了以下错误:

不能将com.android.internal.policy.PhoneLayoutInflater转换为com.flipkart.android.proteus.ProteusLayoutInflater

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2017-12-18 16:18:31

下面是Fragment的一些示例代码,您应该可以开始使用这些代码:

记住将gson-adapter添加到应用程序的build.gradle文件中。

代码语言:javascript
复制
dependencies {
    compile 'com.github.flipkart-incubator.proteus:gson-adapter:5.0.0-rc12'
}

在您的片段中,根据以下内容添加和修改:

代码语言:javascript
复制
  // some private fields in the fragment
  private Proteus proteus;
  private ProteusContext context;
  private ProteusLayoutInflater layoutInflater;
  private Gson gson;

  public void onAttach (Activity activity) {
    // create a new instance of the proteus type adapter 
    // for gson and register it with gson. 
    ProteusTypeAdapterFactory adapter = new ProteusTypeAdapterFactory(activity);
    gson = new GsonBuilder().registerTypeAdapterFactory(adapter).create();

    // create a new instance of proteus from the builder
    proteus = new ProteusBuilder().build();
    // get a new context object from proteus
    context = proteus.createContextBuilder(activity).build();

    // this context object has the proteus layout inflater
    layoutInflater = context.getInflater();

    // set the instance of proteus 
    ProteusTypeAdapterFactory.PROTEUS_INSTANCE_HOLDER.setProteus(proteus);
  }

  public ProteusContext getContext() {
    return context;
  }

  public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    String layoutString = loadJSONFromAsset(getContext());

    // use gson to deserialize the string into a Layout object.
    Layout layout = gson.fromJson(layoutString, Layout.class);

    // the use the proteus layout inflater to inflate a new proteus view  
    ProteusView view = layoutInflater.inflate(layout, new ObjectValue());
    return view.getAsView();
  }

这基本上是一个工作的例子,有很大的空间,以加强和改进。您应该直接到git,克隆它,玩演示应用程序,并查看ProteusActivity的代码作为参考实现。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/47865866

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档