无法将Expandable ListView添加到片段中

时间:2016-06-03 10:06:30

标签: java android listview android-fragments

this is the fragment where i want to add the expandable list view the grey colored space below the image of news and update (Click to Open Image)

无法将可扩展ListView添加到片段中以获取错误。

我有一个导航抽屉来浏览新闻和更新片段,其中我想要一个可扩展的列表视图,但我无法添加它我不知道如何解决这个问题

fragment_news_update.xml

<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.example.aakash.myapp.news_update"
android:background="#d3d3d3">


<ImageView
    android:layout_width="match_parent"
    android:layout_height="170dp"
    android:id="@+id/imageView2"
    android:layout_gravity="left|top"
    android:background="@drawable/news_update_top" />

<ExpandableListView
    android:layout_width="wrap_content"
    android:layout_height="340dp"
    android:id="@+id/expListView"
    android:layout_gravity="right|bottom" />

news_update.java

package com.example.aakash.myapp;

 public class news_update extends Fragment{

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


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

ExpandableListAdapter listAdapter;
ExpandableListView expListView;
List<String> listDataHeader;
HashMap<String, List<String>> listDataChild;

{

    // get the listview
    expListView = (ExpandableListView) getView().findViewById(R.id.expListView);

    // Listview on child click listener
    expListView.setOnChildClickListener(new ExpandableListView.OnChildClickListener() {

        @Override

        public boolean onChildClick(ExpandableListView parent, View v,
                                    int groupPosition, int childPosition, long id) {
            Toast.makeText(
                    getActivity().getApplicationContext(),
                    listDataHeader.get(groupPosition)
                            + " : "
                            + listDataChild.get(
                            listDataHeader.get(groupPosition)).get(
                            childPosition), Toast.LENGTH_SHORT)
                    .show();
            return false;
        }
    });

    // preparing list data
    prepareListData();

    listAdapter = new ExpandableListAdapter(this, listDataHeader, listDataChild);

    // setting list adapter
    expListView.setAdapter(listAdapter);
}

/*
 * Preparing the list data
 */
private void prepareListData() {
    listDataHeader = new ArrayList<String>();
    listDataChild = new HashMap<String, List<String>>();

    // Adding child data
    listDataHeader.add("Top 250");
    listDataHeader.add("Now Showing");
    listDataHeader.add("Coming Soon..");

    // Adding child data
    List<String> top250 = new ArrayList<String>();
    top250.add("The Shawshank Redemption");
    top250.add("The Godfather");
    top250.add("The Godfather: Part II");
    top250.add("Pulp Fiction");
    top250.add("The Good, the Bad and the Ugly");
    top250.add("The Dark Knight");
    top250.add("12 Angry Men");

    List<String> nowShowing = new ArrayList<String>();
    nowShowing.add("The Conjuring");
    nowShowing.add("Despicable Me 2");
    nowShowing.add("Turbo");
    nowShowing.add("Grown Ups 2");
    nowShowing.add("Red 2");
    nowShowing.add("The Wolverine");

    List<String> comingSoon = new ArrayList<String>();
    comingSoon.add("2 Guns");
    comingSoon.add("The Smurfs 2");
    comingSoon.add("The Spectacular Now");
    comingSoon.add("The Canyons");
    comingSoon.add("Europa Report");

    listDataChild.put(listDataHeader.get(0), top250); // Header, Child data
    listDataChild.put(listDataHeader.get(1), nowShowing);
    listDataChild.put(listDataHeader.get(2), comingSoon);
}

}

ExpandableListAdapter.java

package info.androidhive.expandablelistview;


  public class ExpandableListAdapter extends BaseExpandableListAdapter {

private Context _context;
private List<String> _listDataHeader; // header titles
// child data in format of header title, child title
private HashMap<String, List<String>> _listDataChild;

public ExpandableListAdapter(Context context, List<String> listDataHeader,
                             HashMap<String, List<String>> listChildData) {
    this._context = context;
    this._listDataHeader = listDataHeader;
    this._listDataChild = listChildData;
}

@Override
public Object getChild(int groupPosition, int childPosititon) {
    return this._listDataChild.get(this._listDataHeader.get(groupPosition))
            .get(childPosititon);
}

@Override
public long getChildId(int groupPosition, int childPosition) {
    return childPosition;
}

@Override
public View getChildView(int groupPosition, final int childPosition,
                         boolean isLastChild, View convertView, ViewGroup parent) {

    final String childText = (String) getChild(groupPosition, childPosition);

    if (convertView == null) {
        LayoutInflater infalInflater = (LayoutInflater) this._context
                .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        convertView = infalInflater.inflate(R.layout.list_item, null);
    }

    TextView txtListChild = (TextView) convertView
            .findViewById(R.id.lblListItem);

    txtListChild.setText(childText);
    return convertView;
}

@Override
public int getChildrenCount(int groupPosition) {
    return this._listDataChild.get(this._listDataHeader.get(groupPosition))
            .size();
}

@Override
public Object getGroup(int groupPosition) {
    return this._listDataHeader.get(groupPosition);
}

@Override
public int getGroupCount() {
    return this._listDataHeader.size();
}

@Override
public long getGroupId(int groupPosition) {
    return groupPosition;
}

@Override
public View getGroupView(int groupPosition, boolean isExpanded,
                         View convertView, ViewGroup parent) {
    String headerTitle = (String) getGroup(groupPosition);
    if (convertView == null) {
        LayoutInflater infalInflater = (LayoutInflater) this._context
                .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        convertView = infalInflater.inflate(R.layout.list_group, null);
    }

    TextView lblListHeader = (TextView) convertView
            .findViewById(R.id.lblListHeader);
    lblListHeader.setTypeface(null, Typeface.BOLD);
    lblListHeader.setText(headerTitle);

    return convertView;
}

@Override
public boolean hasStableIds() {
    return false;
}

@Override
public boolean isChildSelectable(int groupPosition, int childPosition) {
    return true;
}

}

MainActivity.java

package com.example.aakash.myapp;

    public class MainActivity extends AppCompatActivity
    implements NavigationView.OnNavigationItemSelectedListener  {

NavigationView navigationView = null;
Toolbar toolbar=null;


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



    //set an initial fragment
    home fragment = new home();
    android.support.v4.app.FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
    fragmentTransaction.replace(R.id.fragment_container,fragment);
    fragmentTransaction.commit();




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

    FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
    fab.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Snackbar.make(view, "Not Available Right Now !!", Snackbar.LENGTH_SHORT)
                    .setAction("Action", null).show();
        }
    });

    DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
    ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
        this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
    drawer.setDrawerListener(toggle);
    toggle.syncState();

    navigationView = (NavigationView) findViewById(R.id.nav_view);
    navigationView.setNavigationItemSelectedListener(this);
}

@Override
public void onBackPressed() {
    DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
    if (drawer.isDrawerOpen(GravityCompat.START)) {
        drawer.closeDrawer(GravityCompat.START);
    } else {
        super.onBackPressed();
    }
}

@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;
}

@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);
}

@SuppressWarnings("StatementWithEmptyBody")
@Override
public boolean onNavigationItemSelected(MenuItem item) {
    // Handle navigation view item clicks here.
    int id = item.getItemId();
    if (id == R.id.nav_home) {

        home fragment = new home();
        android.support.v4.app.FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
        fragmentTransaction.replace(R.id.fragment_container,fragment);
        fragmentTransaction.commit();


        // Handle the camera action
    }
    if (id == R.id.nav_news_updates) {

        news_update fragment = new news_update();
        android.support.v4.app.FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
        fragmentTransaction.replace(R.id.fragment_container,fragment);
        fragmentTransaction.commit();


        // Handle the camera action
    } else if (id == R.id.nav_admission) {

        Gallery_Fragment fragment = new Gallery_Fragment();
        android.support.v4.app.FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
        fragmentTransaction.replace(R.id.fragment_container,fragment);
        fragmentTransaction.commit();

    } else if (id == R.id.nav_results) {

    } else if (id == R.id.nav_l_o_h) {

    }  else if (id == R.id.nav_contact_us) {

    }

    DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
    drawer.closeDrawer(GravityCompat.START);
    return true;
}

}

的AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
 <manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.aakash.myapp" >

<application
    android:allowBackup="true"
    android:icon="@mipmap/ic_launcher"
    android:label="@string/app_name"
    android:supportsRtl="true"
    android:theme="@style/AppTheme" >
    <activity
        android:name=".MainActivity"
        android:label="@string/app_name"
        android:theme="@style/AppTheme.NoActionBar" >
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
   </application>

Click to open Screenshot

error_log中

06-03 22:20:05.587 3547-3547/com.example.aakash.myapp E/AndroidRuntime: FATAL EXCEPTION: main
                                                                    Process: com.example.aakash.myapp, PID: 3547
                                                                    java.lang.NullPointerException: Attempt to invoke virtual method 'android.view.View android.app.Activity.findViewById(int)' on a null object reference
                                                                        at com.example.aakash.myapp.news_update.<init>(news_update.java:46)
                                                                        at com.example.aakash.myapp.MainActivity.onNavigationItemSelected(MainActivity.java:111)
                                                                        at android.support.design.widget.NavigationView$1.onMenuItemSelected(NavigationView.java:151)
                                                                        at android.support.v7.view.menu.MenuBuilder.dispatchMenuItemSelected(MenuBuilder.java:811)
                                                                        at android.support.v7.view.menu.MenuItemImpl.invoke(MenuItemImpl.java:152)
                                                                        at android.support.v7.view.menu.MenuBuilder.performItemAction(MenuBuilder.java:958)
                                                                        at android.support.design.internal.NavigationMenuPresenter$1.onClick(NavigationMenuPresenter.java:318)
                                                                        at android.view.View.performClick(View.java:5198)
                                                                        at android.view.View$PerformClick.run(View.java:21147)
                                                                        at android.os.Handler.handleCallback(Handler.java:739)
                                                                        at android.os.Handler.dispatchMessage(Handler.java:95)
                                                                        at android.os.Looper.loop(Looper.java:148)
                                                                        at android.app.ActivityThread.main(ActivityThread.java:5417)
                                                                        at java.lang.reflect.Method.invoke(Native Method)
                                                                        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
                                                                        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)

2 个答案:

答案 0 :(得分:0)

为什么要将news_update扩展到FragmentActivity。只是用Fragment扩展。 FragmentActivity不是一个片段,它是Activity的子类,因此您收到错误news_update cannot be converted to Fragment

import android.support.v4.app.Fragment;
 public class news_update extends Fragment{}

答案 1 :(得分:0)

Fragment没有setContentView()方法,您无法直接在findViewById()中使用Fragment方法。您可以参考阅读this。而不是setContentView(),您必须在链接中提及资源文件,并将膨胀的ViewGroup收集到本地ViewGroup中。一旦你拥有了那个膨胀的ViewGroup,你就可以在那个特定的ViewGroup中找到任何视图。

首先执行所有这些操作,阅读链接并尝试运行该应用程序。您的问题将得到解决