为什么无法在android片段的工具栏中显示UP按钮图标?

时间:2016-12-14 07:05:25

标签: android android-fragments

我正在android中开发一个新闻应用程序。我有以下内容

  • Android抽屉
  • 主要活动
  • 新闻项目片段
  • 新闻Itemdetails Fragment
  • 工具栏

News Item Fragment是应用程序中的第一页。它有一个列表视图,显示新闻项目。当用户点击列表视图中的项目时,它会打开第二页(News Itemdetails Fragment)。我希望在第二页处于活动状态时在工具栏上显示“向上”按钮图标,以便用户可以再次返回到第一页。为了显示工具栏中的UP按钮,我在'News Itemdetails Fragment'(第二页)中尝试了'setDisplayHomeAsUpEnabled',但是当在'News Item Fragment'(第一页)中点击一个项目时,它会抛出错误。

我已提供以下详细信息供您参考。

新闻项目片段

package com.uss.navigationdrawer3;

import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Toast;

public class HomeFragment extends Fragment {
    // Listview Adapter
    ArrayAdapter<String> adapter;
    // Search EditText
    EditText inputSearch;

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


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view=inflater.inflate(R.layout.fragment_home, container, false);
        String[] planets = new String[] { "News Item 1", "News Item 2", "News Item 3","News Item 4","News Item 5","News Item 6"
        };
        final ListView listView=(ListView) view.findViewById(R.id.list_view_fragment_home);

        //adapter = new ArrayAdapter<String>(this, R.layout.list_item, R.id.product_name, planets);
        adapter=new ArrayAdapter<String>(getActivity(),R.layout.list_item,R.id.product_name,planets);
        //ArrayAdapter adapter = new ArrayAdapter(this,
        //        R.layout.list_item, R.id.product_name, planets);

        // Assign adapter to ListView
        listView.setAdapter(adapter);

        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> arg0, View arg1,
                                    int position, long arg3) {
                // TODO Auto-generated method stub
                int itemPosition     = position;

                // ListView Clicked item value
                String  itemValue    = (String) listView.getItemAtPosition(position);

                // Show Alert
                Toast.makeText(getActivity(),
                        "Position :"+itemPosition+"  ListItem : " +itemValue , Toast.LENGTH_LONG)
                        .show();


                FragmentTransaction fragmentTransaction=getFragmentManager().beginTransaction();
                fragmentTransaction.replace(R.id.main_container,new MessageFragment());
                fragmentTransaction.addToBackStack(null);
                fragmentTransaction.commit();

                //getSupportActionBar().setTitle("Message Fragment");
            }
        });
        inputSearch = (EditText) view.findViewById(R.id.inputSearch);
        inputSearch.addTextChangedListener(new TextWatcher() {

       @Override
       public void onTextChanged(CharSequence cs, int arg1, int arg2, int arg3) {
           // When user changed the Text
           HomeFragment.this.adapter.getFilter().filter(cs);
       }

       @Override
       public void beforeTextChanged(CharSequence arg0, int arg1, int arg2,
                                     int arg3) {
           // TODO Auto-generated method stub

       }

       @Override
       public void afterTextChanged(Editable arg0) {
           // TODO Auto-generated method stub
       }


   }
        );


        // Inflate the layout for this fragment
        return view;
    }

}

新闻Itemdetails Fragment

package com.uss.navigationdrawer3;


import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

/**
 * A simple {@link Fragment} subclass.
 */
public class MessageFragment extends Fragment{

    Toolbar toolbar;

    public MessageFragment() {
        // 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_message, container, false);
        View view=inflater.inflate(R.layout.fragment_message, container, false);

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


        AppCompatActivity activity = (AppCompatActivity) getActivity();
        activity.setSupportActionBar(toolbar);
        if (activity != null) {
            ActionBar ab = activity.getSupportActionBar();
            if (ab != null) {
                ab.setDisplayHomeAsUpEnabled(true);
            }
        }

        toolbar.setTitle("Title");

        return view;
    }

}

错误

12-14 12:06:37.675    2005-2005/com.uss.navigationdrawer3 D/AndroidRuntime﹕ Shutting down VM
    --------- beginning of crash
12-14 12:06:37.675    2005-2005/com.uss.navigationdrawer3 E/AndroidRuntime﹕ FATAL EXCEPTION: main
    Process: com.uss.navigationdrawer3, PID: 2005
    java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.CharSequence android.support.v7.widget.Toolbar.getTitle()' on a null object reference
        at android.support.v7.internal.widget.ToolbarWidgetWrapper.<init>(ToolbarWidgetWrapper.java:94)
        at android.support.v7.internal.widget.ToolbarWidgetWrapper.<init>(ToolbarWidgetWrapper.java:87)
        at android.support.v7.internal.app.ToolbarActionBar.<init>(ToolbarActionBar.java:77)
        at android.support.v7.app.AppCompatDelegateImplV7.setSupportActionBar(AppCompatDelegateImplV7.java:198)
        at android.support.v7.app.AppCompatActivity.setSupportActionBar(AppCompatActivity.java:96)
        at com.uss.navigationdrawer3.MessageFragment.onCreateView(MessageFragment.java:36)
        at android.support.v4.app.Fragment.performCreateView(Fragment.java:1789)
        at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:955)
        at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1138)
        at android.support.v4.app.BackStackRecord.run(BackStackRecord.java:740)
        at android.support.v4.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1501)
        at android.support.v4.app.FragmentManagerImpl$1.run(FragmentManager.java:458)
        at android.os.Handler.handleCallback(Handler.java:739)
        at android.os.Handler.dispatchMessage(Handler.java:95)
        at android.os.Looper.loop(Looper.java:135)
        at android.app.ActivityThread.main(ActivityThread.java:5221)
        at java.lang.reflect.Method.invoke(Native Method)
        at java.lang.reflect.Method.invoke(Method.java:372)
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:899)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694)
12-14 12:06:37.867    2005-2017/com.uss.navigationdrawer3 I/art﹕ Background sticky concurrent mark sweep GC freed 3409(281KB) AllocSpace objects, 0(0B) LOS objects, 18% free, 1831KB/2MB, paused 77.322ms total 183.824ms
12-14 12:11:37.853    2005-2005/com.uss.navigationdrawer3 I/Process﹕ Sending signal. PID: 2005 SIG: 9

请在工具栏中按下向上按钮时帮助如何从第二页进入第一页。

1 个答案:

答案 0 :(得分:0)

似乎您已在活动xml中定义了工具栏,并尝试在片段中访问它,返回工具栏值