如何将 运行 java 和 xml 代码(从 api 中获取)放入另一个片段

how to run java and xml code (fetched from api) into another fragment

好的,我将简要定义我 want.I 从 api 中获取 java 代码(用于文本视图、按钮等)的内容,就像这样 --> image description here and Xml code(for textview, button,etc)from api like this--> image description here..what I want is to run these java and xml and display it like this--> enter image description here..我真的不知道该怎么做..任何人都可以帮忙..我会 post up java/xml 代码及其适配器请看..我什么都没做演示片段..我应该在演示片段中做什么???

java:

public class JavaFragment extends Fragment {

    private RecyclerView recyclerView;
    private NextSLJavaAdapter adapter;
    private NextSLModel DescriptList;
    ProgressDialog progressDialog;
    public JavaFragment() {
        // Required empty public constructor
    }


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        return inflater.inflate(R.layout.nextsl_layout, container, false);

    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        Toolbar toolbar = (Toolbar) getView().findViewById(R.id. toolbar );
       // setSupportActionBar( toolbar );
        //if (getSupportActionBar() != null) {
          //  getSupportActionBar().setDisplayHomeAsUpEnabled(true);
           // getSupportActionBar().setDisplayShowHomeEnabled(true);
        //}
        progressDialog = new ProgressDialog(getContext());
        progressDialog.setMessage("Loading....");
        progressDialog.show();
        Intent intent = getActivity().getIntent();
        String title = intent.getStringExtra("title");
        //getSupportActionBar().setTitle(title);
        String id = intent.getStringExtra("idSLnext");
        Log.e("ashwini", String.valueOf(id));


        /*Create handle for the RetrofitInstance interface*/
        SLApiSevice service = SLApiClient.getRetrofitInstance().create(SLApiSevice.class);
        Call<NextSLModel> call = service.getnextslmodel(id);
        call.enqueue(new Callback<NextSLModel>() {
            @Override
            public void onResponse(Call<NextSLModel> call, Response<NextSLModel> response) {
                progressDialog.dismiss();
                DescriptList=response.body();
                generateDataList(DescriptList);
            }

            @Override
            public void onFailure(Call<NextSLModel> call, Throwable t) {
                 progressDialog.dismiss();

                Toast.makeText(getContext(), "Something went wrong...Please try later!", Toast.LENGTH_SHORT).show();
            }
        });

    }
    private void generateDataList(NextSLModel photoList) {
        recyclerView = getView().findViewById(R.id.nextSLrecycle);
        LinearLayoutManager manager = new LinearLayoutManager(getContext());
        recyclerView.setLayoutManager(manager);
        recyclerView.setHasFixedSize(true);
        adapter = new NextSLJavaAdapter(getContext(),photoList);
        recyclerView.setAdapter(adapter);
    }
}

java 适配器:

public class NextSLJavaAdapter extends RecyclerView.Adapter<NextSLJavaAdapter.CustomViewHolder> {

    NextSLModel Slmdel;
    Context context;

    public NextSLJavaAdapter(Context context, NextSLModel employees) {
        this.Slmdel = employees;
        this.context = context;
    }

    @Override
    public CustomViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View itemView = LayoutInflater.from(parent.getContext())
                .inflate(R.layout.nextsl_item, parent, false);

        return new CustomViewHolder(itemView);
    }

    @Override
    public void onBindViewHolder(CustomViewHolder holder, int position) {

        holder.employeeName.setText(Slmdel.getJava());
        Log.e("sl",Slmdel.getJava());


    }

    @Override
    public int getItemCount() {
        return 1;
        //return (employees == null) ? 0 : employees.size();

    }

    public class CustomViewHolder extends RecyclerView.ViewHolder {
        public TextView employeeName;
        TextView textView;

        public CustomViewHolder(View view) {
            super(view);
            employeeName = (TextView) view.findViewById(R.id.detailsStartLearning);
            textView = view.findViewById(R.id.Sl1);
        }
    }
}

xml代码:

public class XMLFragmet extends Fragment {
    private RecyclerView recyclerView;
    private NextSLXmlAdapter adapter;
    private NextSLModel DescriptList;
    ProgressDialog progressDialog;
    public XMLFragmet() {
        // Required empty public constructor
    }


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        return inflater.inflate(R.layout.nextsl_layout, container, false);
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        /*Create handle for the RetrofitInstance interface*/
        progressDialog = new ProgressDialog(getContext());
        progressDialog.setMessage("Loading....");
        progressDialog.show();
        Intent intent = getActivity().getIntent();

        String id = intent.getStringExtra("idSLnext");
        Log.e("ashwini", String.valueOf(id));
        SLApiSevice service = SLApiClient.getRetrofitInstance().create(SLApiSevice.class);
        Call<NextSLModel> call = service.getnextslmodel(id);
        call.enqueue(new Callback<NextSLModel>() {
            @Override
            public void onResponse(Call<NextSLModel> call, Response<NextSLModel> response) {
                 progressDialog.dismiss();
                DescriptList = response.body();
                generateDataList(DescriptList);
            }

            @Override
            public void onFailure(Call<NextSLModel> call, Throwable t) {
                 progressDialog.dismiss();

                Toast.makeText(getContext(), "Something went wrong...Please try later!", Toast.LENGTH_SHORT).show();
            }
        });

    }
    private void generateDataList(NextSLModel photoList) {
        recyclerView = getView().findViewById(R.id.nextSLrecycle);
        LinearLayoutManager manager = new LinearLayoutManager(getContext());
        recyclerView.setLayoutManager(manager);
        recyclerView.setHasFixedSize(true);
        adapter = new NextSLXmlAdapter(getContext(),photoList);
        recyclerView.setAdapter(adapter);
    }
}

xml 适配器:

public class NextSLXmlAdapter extends RecyclerView.Adapter<NextSLXmlAdapter.CustomViewHolder> {

    NextSLModel Slmdel;
    Context context;

    public NextSLXmlAdapter(Context context, NextSLModel employees) {
        this.Slmdel = employees;
        this.context = context;
    }

    @Override
    public CustomViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View itemView = LayoutInflater.from(parent.getContext())
                .inflate(R.layout.nextsl_item, parent, false);

        return new CustomViewHolder(itemView);
    }

    @Override
    public void onBindViewHolder(CustomViewHolder holder, int position) {

        holder.employeeName.setText(Slmdel.getXml());


    }

    @Override
    public int getItemCount() {
        return 1;
        //return (employees == null) ? 0 : employees.size();

    }

    public class CustomViewHolder extends RecyclerView.ViewHolder {
        public TextView employeeName;
        TextView textView;

        public CustomViewHolder(View view) {
            super(view);
            employeeName = (TextView) view.findViewById(R.id.detailsStartLearning);
            textView = view.findViewById(R.id.Sl1);
        }
    }
}

演示 activity:

public class DemoFragment extends Fragment {


        public DemoFragment() {
            // Required empty public constructor
        }


        @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container,
                                 Bundle savedInstanceState) {
            // Inflate the layout for this fragment
            return inflater.inflate(R.layout.fragment_demo, container, false);
        }

        @Override
        public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
            super.onViewCreated(view, savedInstanceState);
           Toast.makeText(getContext(),"hi Edit",Toast.LENGTH_LONG).show();

            Intent intent = getActivity().getIntent();


            String id = intent.getStringExtra("idSLnext");
            Log.e("demo", id);

            if(id.matches("11"))
          {
            ///can't I put logic over here which im getting from api(java and xml)
              Toast.makeText(getContext(),"hi textview",Toast.LENGTH_LONG).show();;
          }
            else if(id.matches("10"))
            {
                Toast.makeText(getContext(),"hi Edit",Toast.LENGTH_LONG).show();
            }
            else if(id.matches("9"))
            {
                Toast.makeText(getContext(),"hi Imageview",Toast.LENGTH_LONG).show();
            }
            else if(id.matches("8"))
            {
                Toast.makeText(getContext(),"hi Button",Toast.LENGTH_LONG).show();
            }
            else if(id.matches("7"))
            {
                Toast.makeText(getContext(),"hi CheckBox",Toast.LENGTH_LONG).show();
            }
            else if(id.matches("6"))
            {
                Toast.makeText(getContext(),"hi RadioButton & RadioGroup",Toast.LENGTH_LONG).show();
            }
            else if(id.matches("5"))
            {
                Toast.makeText(getContext(),"hi DatePicker",Toast.LENGTH_LONG).show();
            }
            else if(id.matches("4"))
            {
                Toast.makeText(getContext(),"hi TimePicker",Toast.LENGTH_LONG).show();
            }
            else if(id.matches("3"))
            {
                Toast.makeText(getContext(),"hi DatePicker",Toast.LENGTH_LONG).show();
            }
            else if(id.matches("2"))
            {
                Toast.makeText(getContext(),"hi Switch",Toast.LENGTH_LONG).show();
            }
            else if(id.matches("1"))
            {
                Toast.makeText(getContext(),"hi Simple & custom Toast",Toast.LENGTH_LONG).show();
        }
    }
}

亲爱的朋友,很遗憾,这是不可能的。正如您所说的来自服务器端的 XML 和 java 代码。对于 运行 java 代码,我们需要对其进行编译,这在移动设备上是不可能的。

希望你明白。但是,您可以做的是创建一个助手 class,它可以解析 JSON 和 returns 从 JSON 和 JSON 生成的包含元素的视图elementType, width, height 等描述,可以在server.xml中预定义。

或者您可以使用 Webview 从服务器加载网页。并在应用程序中使用它。或者对于某些操作使用拦截 java 脚本。

android 从一开始就不支持远程代码注入。框架开发人员可能已经从安全角度以及移动设备的有限计算角度进行了思考。请注意 android 工作室构建过程将这些 java、xml 文件转换为 dex 文件,这在运行时无法完成,因此不受支持。

Important For performance reasons, view inflation relies heavily on pre-processing of XML files that is done at build time. Therefore, it is not currently possible to use LayoutInflater with an XmlPullParser over a plain XML file at runtime.

另一种方法是对视图和属性使用一些 JSON 格式,它会在空白上动态绘制小部件 canvas 会将其添加到布局父级。

例如。

    {
  "type": "LinearLayout",
  "orientation": "vertical",
  "padding": "16dp",
  "children": [{
    "layout_width": "200dp",
    "gravity": "center",
    "type": "TextView",
    "text": "@{user.profile.name}"
  }, {
    "type": "HorizontalProgressBar",
    "layout_width": "200dp",
    "layout_marginTop": "8dp",
    "max": 6000,
    "progress": "@{user.profile.experience}"
  }]
}

这将添加一个 LinearLayout,子元素为 TextViewHorizo​​ntalScrollBar。也可以像下面这样插入数据。

    {
  "user": {
    "profile": {
      "name": "John Doe",
      "experience": 4192
    }
  }
}

关于如何使用这个SDK点击下面link。 https://github.com/flipkart-incubator/proteus

有两种动态添加视图的方法。

  1. 你创建你的 xml 文件。然后使用 LayoutInflater 你将 xml 添加到你的 view .

  2. 或者您可以像 var textview=TextView() 那样动态创建视图 然后 textview.text="xyz"

您需要相对布局或线性布局,其中将使用 addView(); 方法添加它们。

但我的条件是你已经声明了你的视图然后你可以在运行时自定义。

你可以查看example