在android中填充/管理视图的更好方法?

时间:2013-12-18 09:02:35

标签: android uiview views

我曾经在iOS语言中编程,其中每个UIView类都有自己的UIViewController类来管理/填充视图本身。我现在正在尝试编写一个简单的Android应用程序,它从url解析JSONArray,然后填充四个视图,但我不知道如何为每个视图实现一个类,并传递它们的字符串参数来填充它们。你能告诉我实现应用程序逻辑的最佳方法是什么?我有一个带有swipable-tabs的新项目,然后我必须使用片段。这些片段与iOS中的UIView相同吗?请帮帮我。

我这样做了,我想知道它是否正确。我创建了一个具有空白活动的新项目和“可滚动选项卡+滑动”作为导航类型。

我的主要活动:

公共类MyMainActvity扩展了FragmentActivity {

private static String url = "http://www.myurl.it";

static JSONObject jObj = null;
/**
 * The {@link android.support.v4.view.PagerAdapter} that will provide
 * fragments for each of the sections. We use a
 * {@link android.support.v4.app.FragmentPagerAdapter} derivative, which
 * will keep every loaded fragment in memory. If this becomes too memory
 * intensive, it may be best to switch to a
 * {@link android.support.v4.app.FragmentStatePagerAdapter}.
 */
SectionsPagerAdapter mSectionsPagerAdapter;

/**
 * The {@link ViewPager} that will host the section contents.
 */
ViewPager mViewPager;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main_activity);

    new JSONParse().execute();

    // Create the adapter that will return a fragment for each of the three
    // primary sections of the app.
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.menu_main_activity, menu);
    return true;
}

/**
 * A {@link FragmentPagerAdapter} that returns a fragment corresponding to
 * one of the sections/tabs/pages.
 */
public class SectionsPagerAdapter extends FragmentPagerAdapter {

    public SectionsPagerAdapter(FragmentManager fm) {
        super(fm);
    }

    @Override
    public Fragment getItem(int position) {
        // getItem is called to instantiate the fragment for the given page.
        // Return a DummySectionFragment (defined as a static inner class
        // below) with the page number as its lone argument.

        switch (position) {
        case 0:
            {
                HomeSection homeFrag= new HomeSection();
                homeFrag.newInstance(jObj);
                return homeFrag;
            }
        case 1:
        {
            ServiceSection servFrag= new ServiceSection();
            servFrag.newInstance(jObj);
            return servFrag;
        }
        case 2:
            {
                Fragment fragment = new DummySectionFragment();
                Bundle args = new Bundle();
                args.putInt(DummySectionFragment.ARG_SECTION_NUMBER, position + 1);
                fragment.setArguments(args);
                return fragment;
            }
        case 3:
        {
            Fragment fragment = new DummySectionFragment();
            Bundle args = new Bundle();
            args.putInt(DummySectionFragment.ARG_SECTION_NUMBER, position + 1);
            fragment.setArguments(args);
            return fragment;
        }
        }
        return null;
    }

    @Override
    public int getCount() {
        // Show 4 total pages.
        return 4;
    }

    @Override
    public CharSequence getPageTitle(int position) {
        Locale l = Locale.getDefault();
        switch (position) {
        case 0:
            return getString(R.string.title_section1).toUpperCase(l);
        case 1:
            return getString(R.string.title_section2).toUpperCase(l);
        case 2:
            return getString(R.string.title_section3).toUpperCase(l);
        case 3:
            return getString(R.string.title_section4).toUpperCase(l);
        }
        return null;
    }
}

/**
 * A dummy fragment representing a section of the app, but that simply
 * displays dummy text.
 */
public static class DummySectionFragment extends Fragment {
    /**
     * The fragment argument representing the section number for this
     * fragment.
     */
    public static final String ARG_SECTION_NUMBER = "section_number";

    public DummySectionFragment() {
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
        View rootView = inflater.inflate(
                R.layout.fragment_dummy, container, false);
        TextView dummyTextView = (TextView) rootView
                .findViewById(R.id.section_label);
        dummyTextView.setText(Integer.toString(getArguments().getInt(
                ARG_SECTION_NUMBER)));
        return rootView;
    }
}

private class JSONParse extends AsyncTask<String, String, JSONArray> {
    private ProgressDialog pDialog;
    @Override
    protected void onPreExecute() {

        super.onPreExecute();
        pDialog = new ProgressDialog(MyMainActivity.this);
        pDialog.setMessage("Getting Data ...");
        pDialog.setIndeterminate(false);
        pDialog.setCancelable(true);
        pDialog.show();
    }
    @Override
    protected JSONArray doInBackground(String... args) {

        JSONParser jParser= new JSONParser();
        JSONArray json =jParser.getJSONFromUrl(url);

        return json;
    }
    @Override
    protected void onPostExecute(JSONArray json) {

        pDialog.dismiss();
        Log.d("JSONARRAY:", json.toString());

        try {
            JSONObject json_data = json.getJSONObject(0);
            jObj= json_data;

            mSectionsPagerAdapter = new SectionsPagerAdapter(
                    getSupportFragmentManager());

            // Set up the ViewPager with the sections adapter.
            mViewPager = (ViewPager) findViewById(R.id.pager);
            mViewPager.setAdapter(mSectionsPagerAdapter);
        }

        catch(JSONException exception) {

            Log.e("ERROR", exception.getMessage());
        }
    }
}

}

这是我的子类片段之一:

公共类HomeSection扩展Fragment {

JSONObject _jObj;
public HomeSection(){}

public void newInstance(JSONObject jObj) {
    Bundle args = new Bundle();

    _jObj= jObj;

    try{
        String content= _jObj.getString("descrizione");
        args.putString("description", content);
    }
    catch(JSONException exception){

        Log.e("ERROR JSON HOME", exception.getMessage());
    }

    // Put any other arguments
    this.setArguments(args);
}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
        Bundle savedInstanceState) {
    View rootView = inflater.inflate(
            R.layout.fragment_dummy, container, false);
    TextView dummyTextView = (TextView) rootView
            .findViewById(R.id.section_label);
    try {
        dummyTextView.setText(_jObj.getString("descrizione"));
    }
    catch(JSONException exception){

        Log.e("ERROR JSON HOME", exception.getMessage());
    }

    return rootView;
}

}

它可以工作,但我想如果这是填充我的应用程序中的视图的正确方法。然后我不知道在HomeSection类中,我在“newIstance”方法中创建的Bundle是否有效是必要的,因为我在方法onCreateView中的视图中设置了我的文本。请问你能帮帮我吗?感谢

1 个答案:

答案 0 :(得分:0)

没有。碎片不等同于UIView。相当于UIView的是Android View类。但是,在大多数情况下不会直接使用。

与iOS不同,Android不使用纯MVC模式。它使用更像MVP模式的东西(参见MVC pattern on AndroidWhich design patterns are used on Android?)。这里,Activity充当主View容器,是应用程序的主要入口点。

基本上,您可以使用View类的一个子类,如TextView,ImageView等,并将它们放在Activity或Fragment中。

Activity / Fragment将扩展您的视图(在解析XML后从其中创建对象)并将其显示给用户。然后,用户可以与视图进行交互,这些触摸事件将由活动/片段路由到相应的视图,或者由活动/片段本身根据您的逻辑使用。

我建议你阅读这个优秀的Android Bootcamp教程系列,它将真正帮助你学习所有基础知识以及“Android方式”的做法。