所有活动中的导航抽屉和操作栏?

时间:2015-12-15 06:38:46

标签: android navigation

我已经通过扩展基本活动在所有活动上实现了操作栏和导航抽屉,但是当我在子活动导航抽屉中使用setcontent视图时,如何解决这个问题并不起作用!这是我的代码:

包含导航抽屉的MainActivity:

package first.service.precision.servicefirst;

import android.annotation.SuppressLint;
import android.app.ActionBar;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.view.Gravity;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;


public class Main2Activity extends Activity {
    public static ContactView contactView;
    NewContacts newContacts;

    public static LeadRequirementsView _LeadRequirements;
//public ContactView contactView;

   protected DrawerLayout mDrawerLayout;

public static  String mysting;
    private ListView mDrawerList;
    Button butonlead;
    // ActionBarDrawerToggle indicates the presence of Navigation Drawer in the action bar
    protected ActionBarDrawerToggle mDrawerToggle;

    // Title of the action bar
    private String mTitle = "";


    @SuppressLint("NewApi")
    @Override
    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main2);

        final ActionBar ab = getActionBar();
        ab.show();
        // Getting reference to the DrawerLayout
        mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
        ab.setTitle(mTitle);

        mDrawerList = (ListView) findViewById(R.id.drawer_list);

        // Getting reference to the ActionBarDrawerToggle
        mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout,

                R.string.open_drawer,
                R.string.close_drawer) {

            /** Called when drawer is closed */
            public void onDrawerClosed(View view) {

                invalidateOptionsMenu();

            }

            /** Called when a drawer is opened */
            public void onDrawerOpened(View drawerView) {

                invalidateOptionsMenu();
            }


        };

        // Setting DrawerToggle on DrawerLayout
        mDrawerLayout.setDrawerListener(mDrawerToggle);

        // Creating an ArrayAdapter to add items to the listview mDrawerList
        ArrayAdapter<String> adapter = new ArrayAdapter<String>(getApplication(),
                R.layout.drawer_list_item, R.id.title, getResources().getStringArray(R.array.option));

        // Setting the adapter on mDrawerList
        mDrawerList.setAdapter(adapter);

        // Enabling Home button
        ab.setHomeButtonEnabled(true);
        ab.setBackgroundDrawable(new ColorDrawable(Color.parseColor("#53A93F")));
        // Enabling Up navigation
        ab.setIcon(R.drawable.sfwhite);
        ab.show();
        ab.setDisplayHomeAsUpEnabled(true);

        // Setting item click listener for the listview mDrawerList
        mDrawerList.setOnItemClickListener(new OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> parent, View view,
                                    int position, long id) {

                // Getting an array of options
                String[] menuItems = getResources().getStringArray(R.array.option);

                // Currently selected option
                mTitle = menuItems[position];

            //    Fragment fragment = null;
              //  String tag = "";
                switch (position) {
                    case 0:
                        Intent lead=new Intent(getApplicationContext(),LeadActivity.class);
                        startActivity(lead);
                        break;
                    case 1:
                        Intent opportunities=new Intent(getApplicationContext(),OpportunitiesActivity .class);
                        startActivity(opportunities);
                        break;
                    case 2:
                      Intent Accounts=new Intent(getApplicationContext(),AccountsActivity.class);
                        startActivity(Accounts);
                        break;
                    case 3:
                        Intent Contacts=new Intent(getApplicationContext(),Contacts.class);
                        startActivity(Contacts);
                        break;
                    case 4:
                        Intent Competitors=new Intent(getApplicationContext(), Competitors.class);
                        startActivity(Competitors);
                        break;
                    case 5:
                        Intent Acivity=new Intent(getApplicationContext(), Activitites.class);
                        startActivity(Acivity);
                        break;
                    case 6:
                        Intent Reports=new Intent(getApplicationContext(),ReportActivity.class);
                        startActivity(Reports);
                        break;
                    default:
                        break;
                }
            }
        });
    }
    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);

    }
    @Override
    public void onBackPressed() {
    //    int back=getFragmentManager().getBackStackEntryCount();
        if (mDrawerLayout.isDrawerOpen(Gravity.LEFT)) {
            mDrawerLayout.closeDrawer(mDrawerList);

        }
else {
            super.onBackPressed();

        }
    }


    @Override
    protected void onPostCreate(Bundle savedInstanceState) {
        super.onPostCreate(savedInstanceState);
        mDrawerToggle.syncState();
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        if (mDrawerToggle.onOptionsItemSelected(item)) {
            return true;
        }
        return super.onOptionsItemSelected(item);
    }

    /**
     * Called whenever we call invalidateOptionsMenu()
     */
    @Override
    public boolean onPrepareOptionsMenu(Menu menu) {
        // If the drawer is open, hide action items related to the content view
        boolean drawerOpen = mDrawerLayout.isDrawerOpen(mDrawerList);


        return super.onPrepareOptionsMenu(menu);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.main2, menu);
        return super.onCreateOptionsMenu(menu);
    }

 /*   @Override
    public void data(String str, String sl) {
Accounts accounts=(Accounts)getFragmentManager().findFragmentByTag("accounts");
        accounts.datarecieve(str,sl);

    }*/

    /*@Override
    public void dataTo(ContactView contactView) {
        Contactss contactss=(Contactss)getFragmentManager().findFragmentByTag("contact");
      contactss.dataTo(contactView);
    }*/



   /* @Override
    public void DataTransfer(String e) {


    }*/
//
    // @Override
    //  public void DataTransfer(ArrayList<String> e) {
    //     Add obj=(Add)getFragmentManager().findFragmentById(R.id.frag_1);
    //   obj.GetlistContact(e);
    // }
}
  /*  @Override
    public void selectedvalue(String s) {
            Add add=new Add();
            FragmentManager fm=getFragmentManager();
            FragmentTransaction ft=fm.beginTransaction();
            ft.replace(R.id.content_frame,add);
            ft.commit();}
    }
*/

这是扩展基本活动的chlid活动

package first.service.precision.servicefirst;

import android.content.Context;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.ListView;

import java.util.ArrayList;

public class LeadActivity extends Main2Activity {

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

        LayoutInflater inflater = (LayoutInflater) this.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        View contentView = inflater.inflate(R.layout.activity_lead, null, false);
        mDrawerLayout.addView(contentView, 0);
        ArrayList<NewsItem> listContact = GetlistContact();
        ListView lv = (ListView)findViewById(R.id.listView);
        lv.setAdapter(new CustomListAdapter(this, listContact));

    }
    private ArrayList<NewsItem> GetlistContact(){
        ArrayList<NewsItem> contactlist = new ArrayList<NewsItem>();

        NewsItem contact = new NewsItem();
        for(int i=1;i<=30;i++) {
            contact = new NewsItem();
            contact.setHeadline("Yoge " +i);
            contact.setReporterName("Yogeshwaran" + i);
            contact.setLeadsource("Yogan" + i);
            contact.setLeadStatus("open" + i);
            contact.setLeadType("Business"+i);
            contactlist.add(contact);

        }

        return contactlist;
    }
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main2, 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);
    }
}

我试图在子活动中填充listview我可以获得listview但导航抽屉却缺少如何解决这个问题!

3 个答案:

答案 0 :(得分:3)

为此,您可以在XML文件中使用View Stub,这对所有Java文件都是通用的。意味着您应该创建一个单独的XML(即将所有xml文件的公共代码写入此文件)并在不同的java文件(活动文件)中访问此XML文件。 您可以从下面的代码行中更好地理解。 使用查看存根在主/通用XML文件中添加以下内容,其中包含导航抽屉和操作栏。

    <RelativeLayout
        xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:tools="http://schemas.android.com/tools"
        xmlns:app="http://schemas.android.com/apk/res-auto"
        android:id="@+id/Home"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        app:layout_behavior="@string/appbar_scrolling_view_behavior"
        tools:showIn="@layout/activity_home"
        tools:context="com.example.bhuvneshgautam.cityretails.HomeActivity">

        <ViewStub
            android:id="@+id/layout_stub"
            android:inflatedId="@+id/message_layout"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_weight="0.75" />

    </RelativeLayout>

现在在每个java文件中添加以下代码行(活动java文件) 在创建

    ViewStub stub = (ViewStub) findViewById(R.id.layout_stub);
    stub.setLayoutResource(R.layout.home_content);
    View inflated = stub.inflate();

    Toolbar 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, "Replace with your own action", Snackbar.LENGTH_LONG)
                    .setAction("Action", null).show();
        }
    });

现在使用“R.layout.home_content”传递给XML文件名,该文件名包含你想要在不同页面中不同的代码。下面是我项目的一个文件代码,它包含我想要的不同代码在那个文件中。 在home_content.xml

                    <ImageView
                        android:id="@+id/Hpersonalcare"
                        android:layout_width="match_parent"
                        android:layout_height="match_parent"
                        android:src="@drawable/personalcare"
                        android:scaleType="centerCrop"/>

答案 1 :(得分:2)

你必须使用View Stub

           <ViewStub
            android:id="@+id/layout_stub"
            android:inflatedId="@+id/message_layout"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_weight="0.75" /> 
中的

....

Main2Activity.java

public class HomeActivity extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener{

.........................
@Override
protected void onCreate(Bundle savedInstanceState) {
.....................

    ViewStub stub = (ViewStub) findViewById(R.id.lay_stub);
    stub.setLayoutResource(R.layout.home_content);
    View inflated = stub.inflate();

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

    FloatingActionButton fab = (FloatingActionButton)findViewById(R.id.fab);
    fab.setOnClickListener(new View.OnClickListener() {


    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();

答案 2 :(得分:1)

不要再次使用setContentView(...),它会在Main2Activity移除抽屉中覆盖此调用。让你的“主要”Activity是抽象的,并创建protected abstract int getCustomContentView(...),它将在所有扩展Activities中提供,返回您当前在setContentView内传递的ID并在父级中将其展开并添加到Drawer中的容器。它可以在OnCreate内完成,所以在超级之后你可以在孩子的findViewById之后直接打电话

public abstract class Main2Activity extends Activity {

    protected abstract int getCustomContentViewResId();

    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main2);
        LinearLayout container = (LinearLayout) findViewById(R.id.drawer_container);
        int layoutResourceId = getCustomContentView();
        LayoutInflater inflater = (LayoutInflater) this.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        View innerView = inflater.inflate(layoutResourceId , container, true);

        //rest of code

    }

}

铅:

public class LeadActivity extends Main2Activity {

protected int getCustomContentViewResId(){
    return R.layout.activity_lead;
}

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    //setContentView(R.layout.activity_lead);
    // this goes to getCustomContentViewResId

    ListView lv = (ListView)findViewById(R.id.listView);
    // inflating already done in super.onCreate by extended Main2Activity so you may call findViewById directly without setContentView
    }

//rest of code
}