0

请检查我的代码:

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

4

1 回答 1

1

以下是一些示例代码Fragment,可以帮助您入门:

记得添加gson-adapterbuild.gradle您的应用程序的文件中。

dependencies {
    compile 'com.github.flipkart-incubator.proteus:gson-adapter:5.0.0-rc12'
}

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

  // 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的代码以获取参考实现。

于 2017-12-18T16:18:31.150 回答