0

我需要帮助我的第一次滑动LayoutListView...我会在其中显示一些文本,ListView但它不起作用:(

MainActivity.java

package com.evolutio.blocklaunch;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Locale;

import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.app.NavUtils;
import android.support.v4.view.ViewPager;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.TextView;

public class MainActivity extends FragmentActivity {

/**
 * 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;

  private ListView mainListView ;  
  private ArrayAdapter<String> listAdapter ;  

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    // Create the adapter that will return a fragment for each of the three

    // Find the ListView resource.   
    mainListView = (ListView) findViewById( R.id.mainListView );  

    // Create and populate a List of planet names.  
    String[] planets = new String[] { "Mercury", "Venus", "Earth", "Mars",  
                                      "Jupiter", "Saturn", "Uranus", "Neptune"};    
    ArrayList<String> planetList = new ArrayList<String>();  
    planetList.addAll( Arrays.asList(planets) );  

    // Create ArrayAdapter using the planet list.  
    listAdapter = new ArrayAdapter<String>(this, R.layout.news, planetList);  

    // Add more planets. If you passed a String[] instead of a List<String>   
    // into the ArrayAdapter constructor, you must not add more items.   
    // Otherwise an exception will occur.  
    listAdapter.add( "Ceres" );  
    listAdapter.add( "Pluto" );  
    listAdapter.add( "Haumea" );  
    listAdapter.add( "Makemake" );  
    listAdapter.add( "Eris" );  

    // Set the ArrayAdapter as the ListView's adapter.  
    mainListView.setAdapter(listAdapter);

    // primary sections of the app.
    mSectionsPagerAdapter = new SectionsPagerAdapter(
            getSupportFragmentManager());

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

}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.main, 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.
        Fragment fragment = new DummySectionFragment();
        Bundle args = new Bundle();
        args.putInt(DummySectionFragment.ARG_SECTION_NUMBER, position + 1);
        fragment.setArguments(args);
        return fragment;
    }

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

    @Override
    public CharSequence getPageTitle(int position) {
        Locale l = Locale.getDefault();
        int tabLayout = 0;
        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);
        }
        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() {
    }

     public static final String ARG_OBJECT = "object";

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {

            Bundle args = getArguments();
            int position = args.getInt(ARG_OBJECT);

            int tabLayout = 0;
            switch (position) {
            case 0:
            tabLayout = R.layout.news;
            break;
            case 1:
            tabLayout = R.layout.news;
            break;
            case 2:
            tabLayout = R.layout.news;
            break;
            }

            View rootView = inflater.inflate(tabLayout, container, false);
            return rootView;
        }
}

}

XML 文件

activity_main.xml

<android.support.v4.view.ViewPager xmlns:android="http://schemas.android.com/apk/res/android"
   xmlns:tools="http://schemas.android.com/tools"
   android:id="@+id/pager"
   android:layout_width="match_parent"
   android:layout_height="match_parent"
   tools:context=".MainActivity" >

    <!--
   This title strip will display the currently visible page title, as well as the page
   titles for adjacent pages.
   -->

    <android.support.v4.view.PagerTitleStrip
       android:id="@+id/pager_title_strip"
       android:layout_width="match_parent"
       android:layout_height="wrap_content"
       android:layout_gravity="top"
       android:background="#33b5e5"
       android:paddingBottom="4dp"
       android:paddingTop="4dp"
       android:textColor="#fff" />

</android.support.v4.view.ViewPager>

项目.xml

<TextView xmlns:android="http://schemas.android.com/apk/res/android"  
android:id="@+id/rowTextView"  
android:layout_width="fill_parent"  
android:layout_height="wrap_content"  
android:padding="10dp"  
android:textSize="16sp" >  
</TextView>

新闻.xml

<?xml version="1.0" encoding="utf-8"?>  
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"  
 android:orientation="vertical"  
 android:layout_width="fill_parent"  
 android:layout_height="fill_parent">  

    <ListView android:layout_width="fill_parent"  
     android:layout_height="fill_parent"  
     android:id="@+id/mainListView">  
    </ListView>  
</LinearLayout>

错误

03-29 10:01:39.827: D/AndroidRuntime(6902): Shutting down VM
03-29 10:01:39.827: W/dalvikvm(6902): threadid=1: thread exiting with uncaught exception (group=0x2b521930)
03-29 10:01:39.827: E/AndroidRuntime(6902): FATAL EXCEPTION: main
03-29 10:01:39.827: E/AndroidRuntime(6902): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.evolutio.blocklaunch/com.evolutio.blocklaunch.MainActivity}: java.lang.NullPointerException
03-29 10:01:39.827: E/AndroidRuntime(6902):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2307)
03-29 10:01:39.827: E/AndroidRuntime(6902):     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2357)
03-29 10:01:39.827: E/AndroidRuntime(6902):     at android.app.ActivityThread.access$600(ActivityThread.java:153)
03-29 10:01:39.827: E/AndroidRuntime(6902):     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1247)
03-29 10:01:39.827: E/AndroidRuntime(6902):     at android.os.Handler.dispatchMessage(Handler.java:99)
03-29 10:01:39.827: E/AndroidRuntime(6902):     at android.os.Looper.loop(Looper.java:137)
03-29 10:01:39.827: E/AndroidRuntime(6902):     at android.app.ActivityThread.main(ActivityThread.java:5226)
03-29 10:01:39.827: E/AndroidRuntime(6902):     at java.lang.reflect.Method.invokeNative(Native Method)
03-29 10:01:39.827: E/AndroidRuntime(6902):     at java.lang.reflect.Method.invoke(Method.java:511)
03-29 10:01:39.827: E/AndroidRuntime(6902):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:795)
03-29 10:01:39.827: E/AndroidRuntime(6902):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:562)
03-29 10:01:39.827: E/AndroidRuntime(6902):     at dalvik.system.NativeStart.main(Native Method)
03-29 10:01:39.827: E/AndroidRuntime(6902): Caused by: java.lang.NullPointerException
03-29 10:01:39.827: E/AndroidRuntime(6902):     at com.evolutio.blocklaunch.MainActivity.onCreate(MainActivity.java:74)
03-29 10:01:39.827: E/AndroidRuntime(6902):     at android.app.Activity.performCreate(Activity.java:5104)
03-29 10:01:39.827: E/AndroidRuntime(6902):     at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1080)
03-29 10:01:39.827: E/AndroidRuntime(6902):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2261)
03-29 10:01:39.827: E/AndroidRuntime(6902):     ... 11 more
03-29 10:01:42.327: I/Process(6902): Sending signal. PID: 6902 SIG: 9
4

3 回答 3

1

您使用了错误的布局,MainActivity因为您已添加 ListViewNews.xml设置activity_mainMainActivity. 您应该使用News.xmlMainActivity 的布局来初始化带有mainListView ListView 的 mainListView:

setContentView(R.layout.News);
于 2013-03-29T09:06:08.603 回答
0

LogCat 说问题出在 MainActivity 的第 74 行,但我认为真正的问题出在第 53 行:

mainListView = (ListView) findViewById( R.id.mainListView );

我认为 mainListView 是空的,因为这个布局元素在 activity_main.xml 中不存在(也许它是在第 82 行加载的?)

您可以尝试将第 53 和 74 行移到第 82 行之后...

于 2013-03-29T09:17:51.597 回答
0

尝试这个:

package com.kt.listviewexample;

import java.util.ArrayList;
import java.util.Arrays;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;

public class MainActivity extends Activity {

   /** Here two object are created mainListView and fruits of class ListView and String respectively 
    *   fruits is contains a set of data as array type
    */
    private ListView mainListView;
    String[] fruits = {
            "Mango",
            "Pine-Apple",
            "Guava",
            "Apple",
            "Banana",
            "Grapes",
            "Orange",
            "watermilon",
            "Dates",
            "Olive", 
    };

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        // called main UI
        setContentView(R.layout.activity_main);

        //Binding the object of ListView
        mainListView = (ListView) findViewById( R.id.mainlistview ); 

       /**
        * A fruitslist object is created of ArrayList type Which holds all element of array(Mango ,Pine-Apple...) , 
        *  in friutlist object
        */

       ArrayList<String> fruitlist = new ArrayList<String>();  
       fruitlist.addAll(Arrays.asList(fruits)); 

       /** Now all these data are bind with a ListView's object for appearance in android device or emulator
        *  with a parameter of current class , name of Xml file which contain TextView , id of that TextView
        *  and finally object of ArrayList in which we all those data
        */
        mainListView.setAdapter(new ArrayAdapter<String>(this, R.layout.list_view, R.id.rowTextView, fruitlist));

        /** Call of listener when we click on every item of ListView
         * 
         */
        mainListView.setOnItemClickListener(new OnItemClickListener() {
             public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

                // When clicked, show a toast with the TextView text
                if (position == 0) {
                      // do this on first item click
                }

                if (position == 1) {
                      // do this on second item click   
                } else {
                      Toast.makeText(getApplicationContext(), "You have selected " + fruits[position], Toast.LENGTH_SHORT).show();
                }
            }
        });
    }

}
于 2013-03-29T09:22:57.017 回答