如何在每个不同的片段上设置 Action 栏

2019年12月25日 7点热度 0条评论

我是android的新手,我正在制作带有YouTube教程,android.com,stackoverflow等的training字典应用程序。我的字典应用程序有问题。我有3个不同的片段,其中之一显示搜索框而不是应用程序名称。我尝试了网络上的所有隔离,但未成功。我将尝试用图片解释

这是我的主要片段,上面列出了所有单词,应该有搜索框,我的意思是没关系

https://i.imgur.com/YReAm2t.jpg

但这是问题所在。这是我的单词详细信息页面,在工具栏上没有搜索框,它必须是应用程序名称。

https://i.imgur.com/EJx72Lj.jpg

我该如何解决?这是我的代码。

我的字典列表片段(fragment_dictionary.xml)

<?xml version="1.0" encoding="utf-8"?>
<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"
    android:focusable="true"
    android:focusableInTouchMode="true">

   <ListView
       android:id="@+id/dictionaryList"
       android:layout_width="match_parent"
       android:layout_height="match_parent"></ListView>



</FrameLayout>

我的单词详细信息片段(fragment_detail.xml)(有问题的那个)

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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"
    android:orientation="vertical">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="50dp"
        android:orientation="horizontal"
        android:paddingLeft="16dp"
        android:paddingRight="16dp"
        android:elevation="1.46dp"
        android:background="#FDFDFD">


        <TextView
            android:id="@+id/tvWord"
            android:layout_width="0dp"
            android:layout_height="match_parent"
            android:layout_weight="1"
            android:textColor="@color/colorPrimary"
            android:textSize="20sp"
            android:text="A"
            android:gravity="center_vertical"
            />

        <ImageButton
            android:id="@+id/btnVolume"
            android:layout_width="48dp"
            android:layout_height="48dp"
            android:background="?actionBarItemBackground"
            android:src="@drawable/ic_volume" />


        <ImageButton
            android:id="@+id/btnBookmark"
            android:layout_width="48dp"
            android:layout_height="48dp"
            android:background="?actionBarItemBackground"
            android:src="@drawable/ic_bookmark_border"/>


    </LinearLayout>

    <!-- TODO: Update blank fragment layout -->
    <ScrollView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:background="#fff">
    <WebView
        android:id="@+id/tvWordTranslate"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:text="@string/hello_blank_fragment"
        android:background="#fff"/>
    </ScrollView>
</LinearLayout>

我的activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<androidx.drawerlayout.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/drawer_layout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:fitsSystemWindows="true"
    tools:openDrawer="start"
    android:focusable="true"
    android:focusableInTouchMode="true">

    <include
        layout="@layout/app_bar_main"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

    <com.google.android.material.navigation.NavigationView
        android:id="@+id/nav_view"
        android:layout_width="333dp"
        android:layout_height="match_parent"
        android:layout_gravity="start"
        android:fitsSystemWindows="true"
        app:headerLayout="@layout/nav_header_main"
        app:menu="@menu/activity_main_drawer" />

</androidx.drawerlayout.widget.DrawerLayout>


我的app_bar_main.xml

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

    <com.google.android.material.appbar.AppBarLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:theme="@style/AppTheme.AppBarOverlay">

        <androidx.appcompat.widget.Toolbar
            android:id="@+id/toolbar"
            android:layout_width="match_parent"
            android:layout_height="?attr/actionBarSize"
            android:background="?attr/colorPrimary"
            app:popupTheme="@style/AppTheme.PopupOverlay"
            app:contentInsetStartWithNavigation="0dp">


            <EditText
                android:id="@+id/edit_search"
                android:layout_width="match_parent"
                android:layout_height="40dp"
                android:background="@drawable/radius_edit_text"
                android:drawablePadding="3dp"
                android:paddingLeft="5dp"
                android:drawableLeft="@drawable/ic_search"
                android:textColor="#000000"
                android:textSize="20dp"
                android:hint="@string/menu_hint"
                android:textColorHint="#9b9a9a" />

        </androidx.appcompat.widget.Toolbar>

    </com.google.android.material.appbar.AppBarLayout>

    <FrameLayout
        android:id="@+id/fragment_container"
        android:layout_width="match_parent"
        android:layout_height="match_parent"/>



</LinearLayout>

这是我的MainActivity.java

package com.example.dictionary;

import android.annotation.TargetApi;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.view.WindowManager;


import com.google.android.material.floatingactionbutton.FloatingActionButton;
import com.google.android.material.snackbar.Snackbar;

import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;

import androidx.annotation.RequiresApi;
import androidx.core.view.GravityCompat;
import androidx.appcompat.app.ActionBarDrawerToggle;

import android.view.MenuItem;

import com.google.android.material.navigation.NavigationView;

import androidx.drawerlayout.widget.DrawerLayout;

import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentTransaction;

import android.view.Menu;
import android.widget.EditText;
import android.widget.Toast;

import java.util.ArrayList;

public class MainActivity extends AppCompatActivity
        implements NavigationView.OnNavigationItemSelectedListener {

    MenuItem menuSetting;
    Toolbar toolbar;


    DBHelper dbHelper;

    DictionaryFragment dictionaryFragment;
    BookmarkFragment bookmarkFragment;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        toolbar = findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        dbHelper = new DBHelper(this);

        DrawerLayout drawer = findViewById(R.id.drawer_layout);
        NavigationView navigationView = findViewById(R.id.nav_view);
        ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
                this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
        drawer.addDrawerListener(toggle);
        toggle.syncState();
        navigationView.setNavigationItemSelectedListener(this);

        dictionaryFragment = new DictionaryFragment();
        bookmarkFragment = BookmarkFragment.getInstance(dbHelper);
        goToFragment(dictionaryFragment, true);

        dictionaryFragment.setOnFragmentListener(new FragmentListener() {
            @Override
            public void onItemClick(String value) {
                String id =  Global.getState(MainActivity.this,"dict_type");
                int dicType = id == null? R.id.eng_kh:Integer.valueOf(id);
                goToFragment(DetailFragment.getNewInstance(value, dbHelper, dicType), false);
            }
        });
        bookmarkFragment.setOnFragmentListener(new FragmentListener() {
            @Override
            public void onItemClick(String value) {

                String id =  Global.getState(MainActivity.this,"dict_type");
                int dicType = id == null? R.id.eng_kh:Integer.valueOf(id);
                goToFragment(DetailFragment.getNewInstance(value, dbHelper, dicType), false);
            }
        });

        EditText edit_search  = findViewById(R.id.edit_search);
        edit_search.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
                dictionaryFragment.filterValue(charSequence.toString());
            }

            @Override
            public void afterTextChanged(Editable editable) {

            }
        });

        getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN);

    }

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

    @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {

        super.onCreateOptionsMenu(menu);
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        menuSetting = menu.findItem(R.id.action_settings);

    String id =  Global.getState(this,"dict_type");
    if (id != null)
        onOptionsItemSelected(menu.findItem(Integer.valueOf(id)));

    else {
        ArrayList<String> source =dbHelper.getWord(R.id.eng_kh);
    dictionaryFragment.resetDatasource(source);


    }
        return true;
    }

    @TargetApi(Build.VERSION_CODES.LOLLIPOP)
    @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
    @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.eng_kh) {
            Global.saveState(this, "dict_type", String.valueOf(id));
            ArrayList<String> source = dbHelper.getWord(id);
            dictionaryFragment.resetDatasource(source);
            menuSetting.setIcon(getDrawable(R.drawable.ic_lang));
            return true;

        } else if (id==R.id.kh_eng){
            Global.saveState(this, "dict_type", String.valueOf(id));
            ArrayList<String> source = dbHelper.getWord(id);
            dictionaryFragment.resetDatasource(source);
            menuSetting.setIcon(getDrawable(R.drawable.ic_lang2));
            return true;

        }   else if (id==R.id.kh_kh){
            Global.saveState(this, "dict_type", String.valueOf(id));
            ArrayList<String> source = dbHelper.getWord(id);
            dictionaryFragment.resetDatasource(source);
            menuSetting.setIcon(getDrawable(R.drawable.ic_lang3));
            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_bookmark){

            String activeFragment = getSupportFragmentManager().findFragmentById(R.id.fragment_container).getClass().getSimpleName();
            if (!activeFragment.equals(BookmarkFragment.class.getSimpleName())){

            goToFragment(bookmarkFragment, false);
            }
        }

        if (id == R.id.nav_dict){

            String activeFragment = getSupportFragmentManager().findFragmentById(R.id.fragment_container).getClass().getSimpleName();
            if (!activeFragment.equals(DictionaryFragment.class.getSimpleName())){

                goToFragment(dictionaryFragment, false);
            }
        }


        if (id == R.id.nav_share){

            String shareBody = "Here is the share content body";
            Intent shareintent = new Intent();
            shareintent.setAction(Intent.ACTION_SEND);
            shareintent.putExtra(Intent.EXTRA_SUBJECT, shareBody);
            shareintent.putExtra(android.content.Intent.EXTRA_TEXT,  getResources().getString(R.string.paylas));
            shareintent.setType("text/plain");
            startActivity(Intent.createChooser(shareintent, "Paylaş!!!"));
        }

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



    void goToFragment(Fragment fragment, boolean isTop){

        FragmentManager fragmentManager = getSupportFragmentManager();
        FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();


        fragmentTransaction.replace(R.id.fragment_container, fragment);
        if (!isTop)
            fragmentTransaction.addToBackStack(null);
        fragmentTransaction.commit();
    }


    @Override
    public boolean onPrepareOptionsMenu(Menu menu) {

        String activeFragment = getSupportFragmentManager().findFragmentById(R.id.fragment_container).getClass().getSimpleName();
        if (activeFragment.equals(BookmarkFragment.class.getSimpleName())){
            menuSetting.setVisible(false);
            toolbar.findViewById(R.id.edit_search).setVisibility(View.GONE);
            toolbar.setTitle("Bookmark");
        }else  {
            menuSetting.setVisible(true);
            toolbar.findViewById(R.id.edit_search).setVisibility(View.VISIBLE);
            toolbar.setTitle("");
        }
        return true;
    }
}


这一个字detailfragment.java

package com.example.dictionary;

import android.content.Context;
import android.net.Uri;
import android.os.Bundle;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;

import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.WebView;
import android.widget.ImageButton;
import android.widget.TextView;
import android.widget.Toast;


public class DetailFragment extends Fragment {

    private String value = "";
    private TextView tvWord;
    private ImageButton btnBookmark, btnVolume;
    private WebView tvWordTranslate;
    private DBHelper mDBHelper;
    private int mDicType;

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

    public static DetailFragment getNewInstance(String value, DBHelper dbHelper, int dicType){
    DetailFragment fragment = new DetailFragment();
    fragment.value = value;
    fragment.mDBHelper= dbHelper;
    fragment.mDicType= dicType;
    return fragment;
    }

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

    }

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


    @Override
    public void onViewCreated( View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        tvWord = (TextView) view.findViewById(R.id.tvWord);
        tvWordTranslate = (WebView) view.findViewById(R.id.tvWordTranslate);
        btnBookmark = (ImageButton) view.findViewById(R.id.btnBookmark);
        btnVolume = (ImageButton) view.findViewById(R.id.btnVolume);

       final Word word = mDBHelper.getWord(value, mDicType);
       tvWord.setText(word.key);
       tvWordTranslate.loadDataWithBaseURL(null, word.value, "text/html", "utf-8", null);
       Word bookmarkWord = mDBHelper.getWordFromBookmark(value);
       int isMark = bookmarkWord == null? 0:1;

        btnBookmark.setTag(isMark);
        int icon = bookmarkWord == null? R.drawable.ic_bookmark_border:R.drawable.ic_bookmark_fill;
        btnBookmark.setImageResource(icon);


        btnBookmark.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                int i = (int)btnBookmark.getTag();

                if (i==0){
                    btnBookmark.setImageResource(R.drawable.ic_bookmark_fill);
                    btnBookmark.setTag(1);
                    mDBHelper.addBookmark(word);
                } else if (i == 1){
                    btnBookmark.setImageResource(R.drawable.ic_bookmark_border);
                    btnBookmark.setTag(0);
                    mDBHelper.removeBookmark(word);
                }
            }
        });
    }

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
    }

    @Override
    public void onDetach() {
        super.onDetach();
    }


}


这个单词的字典fragment.java

package com.example.dictionary;

import android.content.Context;
import android.net.Uri;
import android.os.Bundle;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;

import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;

import java.util.ArrayList;


public class DictionaryFragment extends Fragment {

    private String value = "Selam Dünyalı";
    private FragmentListener listener;
    ArrayAdapter<String> adapter;
    ListView dicList;
    private ArrayList<String> mSource= new ArrayList<String>();

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


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

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


    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
//        Button myButton = (Button)view.findViewById(R.id.myBtn);
 //       myButton.setOnClickListener(new View.OnClickListener() {
  ///          @Override
  //          public void onClick(View view) {
   //             if (listener!=null)
    //        listener.onItemClick(value);
    //        }
    //    });

        dicList = view.findViewById(R.id.dictionaryList);
        adapter = new ArrayAdapter<String>(getContext(),android.R.layout.simple_list_item_1, mSource);
        dicList.setAdapter(adapter);
        dicList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int position, long l) {
                if (listener!=null)
                listener.onItemClick(mSource.get(position));
            }
        });
    }

    //bundan sonra ikinci sözlük olayı başladı
    public void resetDatasource (ArrayList<String> source){
        mSource=source;
        adapter = new ArrayAdapter<String>(getContext(),android.R.layout.simple_list_item_1, mSource);
        dicList.setAdapter(adapter);

    }

    public void filterValue(String value){
   /// adapter.getFilter().filter(value);



        ///step 6 dakika 5 te bu arama olayı yapıldı, üstteki //koyulan kod direkt arama yapıyordu
        ///// bu aşağıda inaktif edilmiş kod karmaşık bir arama yapıyor üstteki tek satırlık adapter silinip, bu kullanılabilir. ama bu şekilde çok daha iyi

      int size = adapter.getCount();
      for(int i = 0; i<size;i++){
          if (adapter.getItem(i).startsWith(value)){
               dicList.setSelection(i);
             break;
            }

       }
    }



    @Override
    public void onAttach(Context context) {
        super.onAttach(context);

    }

    @Override
    public void onDetach() {
        super.onDetach();  }

        public void setOnFragmentListener(FragmentListener listener){
        this.listener= listener;

        }



}


任何帮助将是巨大的,谢谢。

解决方案如下:

您需要为片段布局添加工具栏,并为每个片段添加单独的menu_item,例如:

<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <android.support.design.widget.AppBarLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content">

        <android.support.v7.widget.Toolbar
            android:id="@+id/toolbar"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:background="?attr/colorPrimary"
            android:minHeight="?attr/actionBarSize"
            app:layout_scrollFlags="scroll|enterAlways"
            app:theme="@style/Toolbar" />

    </android.support.design.widget.AppBarLayout>

    <ListView
       android:id="@+id/dictionaryList"
       android:layout_width="match_parent"
       android:layout_height="match_parent"
       app:layout_behavior="@string/appbar_scrolling_view_behavior"/>

</android.support.design.widget.CoordinatorLayout>

您需要在res文件夹的menu文件夹中创建菜单项:

<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto">

    <item
        android:id="@+id/action_search"
        android:icon="@drawable/ic_menu_search"
        android:title="@string/action_search"
        app:showAsAction="ifRoom" />
</menu>

您需要按如下所示对其进行充气:

override fun onCreateOptionsMenu(menu: Menu): Boolean {
        menuInflater.inflate(R.menu.search_menu, menu)
        return true
}

这应该在res文件夹的Values文件夹的styles.xml中定义:

<style name="Toolbar" parent="ThemeOverlay.AppCompat.Dark.ActionBar" />

您也可以查看
https://github.com/Ali-Rezaei/TMDb-Paging/blob/master/app/src/main/res/layout/activity_main_nav.xml为您的应用程序创建导航抽屉,如图像所示。

Addenda

您应该从MainActivity中删除工具栏和导航抽屉,并将其移至MainFragment。

您的DetailFragment布局应如我所解释。在代码中,您应该将标题作为app_name添加到工具栏:

Toolbar toolbar = findViewById(R.id.toolbar); 
   toolbar.setTitle(R.string.app_name);
   setSupportActionBar(toolbar);

请注意,您的活动或应用程序样式应为:

    <style name="AppTheme" parent="Theme.AppCompat.NoActionBar">