简体   繁体   English

如何在片段类中显示listView?

[英]How to display listView in fragment class?

I'm new in android programming.我是android编程的新手。 I want to try to make simple tab layout app using fragment , how to display listView in a fragment?我想尝试使用fragment制作简单的选项卡布局应用程序,如何在片段中显示 listView? , I have googled and found a solution but it not using fragment class. ,我用谷歌搜索并找到了一个解决方案,但它没有使用片段类。 I can show webview but how to show a listVIew我可以显示 webview 但如何显示 listVIew

My tab1 class:我的tab1类:

       public class Tab1 extends Fragment {
WebView webView;
    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        // get the url to open
        // set up the WebView
        webView = (WebView) getView().findViewById(R.id.webView);
        webView.setWebViewClient(new MyBrowser());
        webView.getSettings().setLoadsImagesAutomatically(true);
        webView.getSettings().setJavaScriptEnabled(true);
        webView.setScrollBarStyle(View.SCROLLBARS_INSIDE_OVERLAY);
        webView.loadUrl("http://www.google.com");
    }
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View v =inflater.inflate(R.layout.tab_1,container,false);
        return v;
    }
    private class MyBrowser extends WebViewClient {
        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            view.loadUrl(url);
            return true;
        }
    }
}

My tab2 class ( i want to display listView here):我的 tab2 类(我想在这里显示 listView):

    public class Tab2 extends Fragment {
    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);

The// ListView activity needs to extend activity class, it doesn't work in a fragment, how to display in a fragment?
    }
    
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View v = inflater.inflate(R.layout.tab_2, container, false);
        return v;
    }

}

Fragment adapter:片段适配器:

public class ViewPagerAdapter extends FragmentStatePagerAdapter {公共类 ViewPagerAdapter 扩展 FragmentStatePagerAdapter {

 CharSequence Titles[]; // This will Store the Titles of the Tabs which are Going to be passed when ViewPagerAdapter is created int NumbOfTabs; // Store the number of tabs, this will also be passed when the ViewPagerAdapter is created // Build a Constructor and assign the passed Values to appropriate values in the class public ViewPagerAdapter(FragmentManager fm,CharSequence mTitles[], int mNumbOfTabsumb) { super(fm); this.Titles = mTitles; this.NumbOfTabs = mNumbOfTabsumb; } //This method return the fragment for the every position in the View Pager @Override public Fragment getItem(int position) { if(position == 0) // if the position is 0 we are returning the First tab { Tab1 tab1 = new Tab1(); return tab1; } else //if (position == 1) // As we are having 2 tabs if the position is now 0 it must be 1 so we are returning second tab { Tab2 tab2 = new Tab2(); return tab2; } // else // { // NewKasus newKasus = new NewKasus(); // return newKasus; // } } // This method return the titles for the Tabs in the Tab Strip @Override public CharSequence getPageTitle(int position) { return Titles[position]; } // This method return the Number of tabs for the tabs Strip @Override public int getCount() { return NumbOfTabs; } }

My MainActivity:我的主要活动:

public class MainActivity extends ActionBarActivity {
//


    // Declaring Your View and Variables

    Toolbar toolbar;
    ViewPager pager;
    ViewPagerAdapter adapter;
    SlidingTabLayout tabs;
    CharSequence Titles[]={"Berita","Kasus","Add Kasus"};
    int Numboftabs =3;


    //
   // bawaaan materal tab
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);


        // Creating The Toolbar and setting it as the Toolbar for the activity

        toolbar = (Toolbar) findViewById(R.id.tool_bar);
        setSupportActionBar(toolbar);


        // Creating The ViewPagerAdapter and Passing Fragment Manager, Titles fot the Tabs and Number Of Tabs.
        adapter =  new ViewPagerAdapter(getSupportFragmentManager(),Titles,Numboftabs);

        // Assigning ViewPager View and setting the adapter
        pager = (ViewPager) findViewById(R.id.pager);
        pager.setAdapter(adapter);

        // Assiging the Sliding Tab Layout View
        tabs = (SlidingTabLayout) findViewById(R.id.tabs);
        tabs.setDistributeEvenly(true); // To make the Tabs Fixed set this true, This makes the tabs Space Evenly in Available width

        // Setting Custom Color for the Scroll bar indicator of the Tab View
        tabs.setCustomTabColorizer(new SlidingTabLayout.TabColorizer() {
            @Override
            public int getIndicatorColor(int position) {
                return getResources().getColor(R.color.tabsScrollColor);
            }
        });

        // Setting the ViewPager For the SlidingTabsLayout
        tabs.setViewPager(pager);



    }


    @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, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }
}

Here i am giving you simple example of showing list In Fragment.在这里,我为您提供了在 Fragment 中显示列表的简单示例。

your fragment first...你的片段先...

public class Tab1 extends ListFragment { 
String[] list_items;    

Tab1(){
}

@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
    View rootView =inflater.inflate(R.layout.tab_1,container,false);
    list_items= getResources().getStringArray(R.array.list);
    setListAdapter(new ArrayAdapter(getActivity(),android.R.layout.simple_list_item_1,list_items);

 return rootView;
}
}

in your strings.xml在你的 strings.xml 中

 <string-array name="list">
         <item>item1</item>
         <item>item1</item>
         <item>item1</item>
         <item>item1</item>
         <item>item1</item>
  </string-array>

your tab_1 layout have to have.. listView.你的 tab_1 布局必须有..listView。 with id android:list this is only necessary when you extend your fragment with ListFragment class. id android:list仅当您使用ListFragment类扩展片段时才需要。 If you simply extend with Fragment then you won't need to add this specific id android:list .如果您只是使用Fragment进行扩展,则无需添加此特定 id android:list

for this example i am giving you need following in your layout...对于这个例子,我给你在你的布局中需要遵循......

<ListView android:id="@id/android:list"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#00FF00"
    android:layout_weight="1"
    />

this is all you need to create listView in fragment.这就是在片段中创建 listView 所需的全部内容。

In your case, you get the data in array and then pass it in listView.在您的情况下,您获取数组中的数据,然后将其传递到 listView。 Here in example i used locally.在示例中,我在本地使用。 Hope it helps!希望能帮助到你!

What is the source of your data?你的数据来源是什么? If you are using ordinary Strings, you could just do it in your onCreateView method, the same way you'd do it in an Activity.如果您使用的是普通字符串,则可以在onCreateView方法中执行此操作,就像在 Activity 中执行此操作的方式相同。

If you are getting the data from a database or network, you'd be better off doing it in the onPostExecute method of an AsyncTask如果您从数据库或网络获取数据,最好在 AsyncTask 的onPostExecute方法中进行

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM