簡體   English   中英

如何將大的個人資料圖片添加到導航抽屜中?

[英]How can I add a large profile picture to my navigation drawer?

因此,幾天前,我開始開發我的第一個應用程序。 這是一個帶有導航抽屜的應用程序,用戶可以在其中設置一些要在導航抽屜中顯示的網站快捷方式。 如果用戶單擊網站,則會在Web視圖中打開。 真的沒什么花哨的,但這是我提出來訓練我的Android知識的一個概念。

我今天早晨在一些幫助下完成了該應用程序的基礎知識,但現在我想在導航抽屜中添加一個大型個人資料圖片。 (您可以在左側在這里看到它: http : //www.droid-life.com/wp-content/uploads/2013/12/new-foursquare.jpg

我知道我應該在導航抽屜中添加一個<ImageView> ,但是每次嘗試使日志不斷顯示我的XML中有垃圾時...

在下面,您可以找到我已經編寫的代碼。 我希望你們能幫助我...

Main.java

package test.webviewapp;

import android.app.Activity;
import android.app.ProgressDialog;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBar;
import android.support.v7.app.ActionBarActivity;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.WebChromeClient;
import android.webkit.WebView;
import android.webkit.WebViewClient;


public class Main
    extends ActionBarActivity
    implements NavigationDrawerFragment.NavigationDrawerCallbacks
{

/**
 * Fragment managing the behaviors, interactions and presentation of the
 * navigation drawer.
 */
private NavigationDrawerFragment mNavigationDrawerFragment;

/**
 * Used to store the last screen title. For use in
 * {@link #restoreActionBar()}.
 */
private CharSequence mTitle;

// we need a class level references to some objects to be able to modify the
//   target address outside of onCreate()
private WebView myWebView;
private ActionBar actionBar;
private ProgressDialog progressDialog;

// keep the pair of String arrays of site names and addresses
private String[] siteNames;
private String[] siteAddresses;

private static final String TAG = "MainActivity";

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

    // grab the needed website arrays
    siteNames = getResources().getStringArray(R.array.site_names);
    siteAddresses = getResources().getStringArray(R.array.site_addresses);

    // set up WebView. initial page load comes from NavDrawerFragment attach
    myWebView = (WebView) findViewById(R.id.main_webview);
    myWebView.getSettings().setJavaScriptEnabled(true);
    myWebView.setWebChromeClient(new WebChromeClient());
    myWebView.setWebViewClient(new WebViewClient()
    {

        @Override
        public void onPageFinished(WebView view, String url)
        {
            // when a page has finished loading dismiss any progress dialog
            if (progressDialog != null && progressDialog.isShowing())
            {
                progressDialog.dismiss();
            }
            String javascript="javascript:"+
                                        "document.getElementById('menu-toggle').css('display','none');";
            myWebView.evaluateJavascript(javascript, null);
        }
    });

    // Set up the drawer.
    mNavigationDrawerFragment = (NavigationDrawerFragment) getSupportFragmentManager()
            .findFragmentById(R.id.navigation_drawer);
    mNavigationDrawerFragment.setUp(R.id.navigation_drawer,
            (DrawerLayout) findViewById(R.id.drawer_layout));
}

@Override
public void onNavigationDrawerItemSelected(int siteIndex)
{
    // user selected page load
    Log.d(TAG, "(onNavSelect) received index: " + siteIndex);
    loadWebPage(siteIndex);
}

public void onSectionAttached(int siteIndex)
{
    // initial page load. not user selected.
    loadWebPage(siteIndex);
}

public void restoreActionBar()
{
    actionBar = getSupportActionBar();
    actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_STANDARD);
    actionBar.setDisplayShowTitleEnabled(true);
    actionBar.setTitle(mTitle);
}

private void loadWebPage(int siteIndex)
{
    // lets show a progress indicator instead of a blank screen
    if (progressDialog == null)
    {
        initProgressDialog();
    }
    progressDialog.show();

    // load the page
    Log.d(TAG, "(loadWebPage) Loading page: " + siteNames[siteIndex] + "("
            + siteAddresses[siteIndex] + ")");
    mTitle = siteNames[siteIndex];
    if (actionBar == null)
    {
        restoreActionBar();
    }
    else
    {
        actionBar.setTitle(mTitle);
    }
    myWebView.getSettings().setJavaScriptEnabled(true);
    myWebView.loadUrl(siteAddresses[siteIndex]);
    myWebView.loadUrl(siteAddresses[siteIndex]);

    // progressDialog gets dismissed above in WebViewclient declaration
}

private void initProgressDialog()
{
    progressDialog = new ProgressDialog(this, ProgressDialog.STYLE_SPINNER);
    progressDialog.setIndeterminate(true);
    progressDialog.setMessage(getString(R.string.page_load_progress_message));
}


@Override
public boolean onCreateOptionsMenu(Menu menu)
{
    if (!mNavigationDrawerFragment.isDrawerOpen())
    {
        // Only show items in the action bar relevant to this screen
        // if the drawer is not showing. Otherwise, let the drawer
        // decide what to show in the action bar.
        getMenuInflater().inflate(R.menu.global, menu);
        restoreActionBar();
        return true;
    }
    return super.onCreateOptionsMenu(menu);
}

@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.
    if (actionBar == null)
    {
        restoreActionBar();
    }
    else
    {

    }
    int id = item.getItemId();
    if (id == R.id.action_settings)
    {
        myWebView.loadUrl(settingsview);
        myWebView.loadUrl(settingsview);
        actionBar.setTitle("Settings");
        return true;
    }
    return super.onOptionsItemSelected(item);
}

/**
 * A placeholder fragment containing a simple view.
 */
public static class PlaceholderFragment
        extends Fragment
{

    /**
     * The fragment argument representing the section number for this
     * fragment.
     */
    private static final String ARG_SELECTED_SITE_INDEX = "selected_site_index";

    /**
     * Returns a new instance of this fragment for the given section
     * number.
     */
    public static PlaceholderFragment newInstance(int siteIndex)
    {
        PlaceholderFragment fragment = new PlaceholderFragment();
        Bundle args = new Bundle();
        args.putInt(ARG_SELECTED_SITE_INDEX, siteIndex);
        fragment.setArguments(args);
        return fragment;
    }

    public PlaceholderFragment()
    {}

    @Override
    public View onCreateView(LayoutInflater inflater,
                             ViewGroup container,
                             Bundle savedInstanceState)
    {
        View rootView = inflater.inflate(R.layout.fragment_main, container, false);
        return rootView;
    }

    @Override
    public void onAttach(Activity activity)
    {
        super.onAttach(activity);
        // Here is where you can define the default page you want loaded
        //  or if you want to save/restore the last page viewed etc.
        ((Main) activity)
                .onSectionAttached(getArguments().getInt(ARG_SELECTED_SITE_INDEX));
    }
}

}

NavigationDrawerFragment.java

package test.webviewapp;

import android.app.Activity;
import android.content.SharedPreferences;
import android.content.res.Configuration;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.support.v4.app.ActionBarDrawerToggle;
import android.support.v4.app.Fragment;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBar;
import android.support.v7.app.ActionBarActivity;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;


/**
 * Fragment used for managing interactions for and presentation of a
 * navigation drawer. See the <a href=
 * "https://developer.android.com/design/patterns/navigation-drawer.html#Interaction"
 * > design guidelines</a> for a complete explanation of the behaviors
 * implemented here.
 */
public class NavigationDrawerFragment
    extends Fragment
    implements AdapterView.OnItemClickListener
{

private String[] siteNames;
private static final String TAG = "NavDrawerFrag";
/**
 * Remember the position of the selected item.
 */
private static final String STATE_SELECTED_POSITION = "selected_navigation_drawer_position";

/**
 * Per the design guidelines, you should show the drawer on launch until
 * the user manually expands it. This shared preference tracks this.
 */
private static final String PREF_USER_LEARNED_DRAWER = "navigation_drawer_learned";

/**
 * A pointer to the current callbacks instance (the Activity).
 */
private NavigationDrawerCallbacks mCallbacks;

/**
 * Helper component that ties the action bar to the navigation drawer.
 */
private ActionBarDrawerToggle mDrawerToggle;

private DrawerLayout mDrawerLayout;
private ListView mDrawerListView;
private View mFragmentContainerView;

private int mCurrentSelectedPosition = 0;
private boolean mFromSavedInstanceState;
private boolean mUserLearnedDrawer;

public NavigationDrawerFragment()
{}

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

    // Read in the flag indicating whether or not the user has demonstrated awareness of the
    // drawer. See PREF_USER_LEARNED_DRAWER for details.
    SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(getActivity());
    mUserLearnedDrawer = sp.getBoolean(PREF_USER_LEARNED_DRAWER, false);

    if (savedInstanceState != null)
    {
        mCurrentSelectedPosition = savedInstanceState.getInt(STATE_SELECTED_POSITION);
        mFromSavedInstanceState = true;
    }

    // Select either the default item (0) or the last selected item.
    // too early to select an item
    //selectItem(mCurrentSelectedPosition);
}

@Override
public void onActivityCreated(Bundle savedInstanceState)
{
    super.onActivityCreated(savedInstanceState);
    // Indicate that this fragment would like to influence the set of actions in the action bar.
    setHasOptionsMenu(true);
    selectItem(mCurrentSelectedPosition);
}

@Override
public View onCreateView(LayoutInflater inflater,
                         ViewGroup container,
                         Bundle savedInstanceState)
{
    siteNames = getActivity().getResources().getStringArray(R.array.site_names);
    Log.d(TAG, "number of sites loaded: " + siteNames.length);
    mDrawerListView = (ListView) inflater.inflate(R.layout.fragment_navigation_drawer,
            container,
            false);
    // neater to implement OnItemClickListener and define onClick() later
    mDrawerListView.setOnItemClickListener(this);
    String[] siteNames = getActivity().getResources().getStringArray(R.array.site_names);
    mDrawerListView.setAdapter(new ArrayAdapter<String>(getActionBar().getThemedContext(),
            android.R.layout.simple_list_item_1, android.R.id.text1, siteNames));
    mDrawerListView.setItemChecked(mCurrentSelectedPosition, true);
    return mDrawerListView;
}

public boolean isDrawerOpen()
{
    return mDrawerLayout != null && mDrawerLayout.isDrawerOpen(mFragmentContainerView);
}

/**
 * Users of this fragment must call this method to set up the navigation
 * drawer interactions.
 *
 * @param fragmentId
 *        The android:id of this fragment in its activity's layout.
 * @param drawerLayout
 *        The DrawerLayout containing this fragment's UI.
 */
public void setUp(int fragmentId, DrawerLayout drawerLayout)
{
    mFragmentContainerView = getActivity().findViewById(fragmentId);
    mDrawerLayout = drawerLayout;

    // set a custom shadow that overlays the main content when the drawer opens
    //mDrawerLayout.setDrawerShadow(R.drawable.drawer_shadow, GravityCompat.START);
    // set up the drawer's list view with items and click listener

    ActionBar actionBar = getActionBar();
    actionBar.setDisplayHomeAsUpEnabled(true);
    actionBar.setHomeButtonEnabled(true);

    // ActionBarDrawerToggle ties together the the proper interactions
    // between the navigation drawer and the action bar app icon.
    mDrawerToggle = new ActionBarDrawerToggle(getActivity(), mDrawerLayout,
            R.drawable.ic_drawer, R.string.navigation_drawer_open,
            R.string.navigation_drawer_close)
    {

        @Override
        public void onDrawerClosed(View drawerView)
        {
            super.onDrawerClosed(drawerView);
            if (!isAdded())
            {
                return;
            }

            getActivity().supportInvalidateOptionsMenu(); // calls onPrepareOptionsMenu()
        }

        @Override
        public void onDrawerOpened(View drawerView)
        {
            super.onDrawerOpened(drawerView);
            if (!isAdded())
            {
                return;
            }

            if (!mUserLearnedDrawer)
            {
                // The user manually opened the drawer; store this flag to prevent auto-showing
                // the navigation drawer automatically in the future.
                mUserLearnedDrawer = true;
                SharedPreferences sp = PreferenceManager
                        .getDefaultSharedPreferences(getActivity());
                sp.edit().putBoolean(PREF_USER_LEARNED_DRAWER, true).apply();
            }

            getActivity().supportInvalidateOptionsMenu(); // calls onPrepareOptionsMenu()
        }
    };

    // If the user hasn't 'learned' about the drawer, open it to introduce them to the drawer,
    // per the navigation drawer design guidelines.
    if (!mUserLearnedDrawer && !mFromSavedInstanceState)
    {
        mDrawerLayout.openDrawer(mFragmentContainerView);
    }

    // Defer code dependent on restoration of previous instance state.
    mDrawerLayout.post(new Runnable()
    {

        @Override
        public void run()
        {
            mDrawerToggle.syncState();
        }
    });

    mDrawerLayout.setDrawerListener(mDrawerToggle);
}

private void selectItem(int siteIndex)
{
    mCurrentSelectedPosition = siteIndex;
    if (mDrawerListView != null)
    {
        Log.d(TAG, "(select) list ok");
        mDrawerListView.setItemChecked(siteIndex, true);
    }
    if (mDrawerLayout != null)
    {
        Log.d(TAG, "(select) drawer ok");
        mDrawerLayout.closeDrawer(mFragmentContainerView);
    }
    if (mCallbacks != null)
    {
        Log.d(TAG, "(select) callback...");
        mCallbacks.onNavigationDrawerItemSelected(siteIndex);
    }
}

@Override
public void onAttach(Activity activity)
{
    super.onAttach(activity);
    try
    {
        mCallbacks = (NavigationDrawerCallbacks) activity;
    }
    catch (ClassCastException e)
    {
        throw new ClassCastException("Activity must implement NavigationDrawerCallbacks.");
    }
}

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

@Override
public void onSaveInstanceState(Bundle outState)
{
    super.onSaveInstanceState(outState);
    outState.putInt(STATE_SELECTED_POSITION, mCurrentSelectedPosition);
}

@Override
public void onConfigurationChanged(Configuration newConfig)
{
    super.onConfigurationChanged(newConfig);
    // Forward the new configuration the drawer toggle component.
    mDrawerToggle.onConfigurationChanged(newConfig);
}

@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater)
{
    // If the drawer is open, show the global app actions in the action bar. See also
    // showGlobalContextActionBar, which controls the top-left area of the action bar.
    if (mDrawerLayout != null && isDrawerOpen())
    {
        inflater.inflate(R.menu.global, menu);
        showGlobalContextActionBar();
    }
    super.onCreateOptionsMenu(menu, inflater);
}

@Override
public boolean onOptionsItemSelected(MenuItem item)
{
    if (mDrawerToggle.onOptionsItemSelected(item))
    {
        //fragment = new PlanetFragment();
    }
    return super.onOptionsItemSelected(item);
}

/**
 * Per the navigation drawer design guidelines, updates the action bar to
 * show the global app 'context', rather than just what's in the current
 * screen.
 */
private void showGlobalContextActionBar()
{
    ActionBar actionBar = getActionBar();
    actionBar.setDisplayShowTitleEnabled(true);
    actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_STANDARD);
    actionBar.setTitle(R.string.app_name);
}

private ActionBar getActionBar()
{
    return ((ActionBarActivity) getActivity()).getSupportActionBar();
}

@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id)
{
    Log.i(TAG, "(Click) index: " + position);
    Log.i(TAG, "(Click) site: " + siteNames[position]);
    selectItem(position);
}

/**
 * Callbacks interface that all activities using this fragment must
 * implement.
 */
public static interface NavigationDrawerCallbacks
{

    /**
     * Called when an item in the navigation drawer is selected.
     */
    void onNavigationDrawerItemSelected(int position);
}

}

activity_main.xml中

<?xml version="1.0" encoding="utf-8"?>
<android.support.v4.widget.DrawerLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent">

    <WebView xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/main_webview"
    android:layout_width="match_parent"
    android:layout_height="match_parent"/>


    <fragment
    android:id="@+id/navigation_drawer"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_gravity="start"
    android:name="test.webdrawerapp.NavigationDrawerFragment"
    tools:layout="@layout/fragment_navigation_drawer"/>

</android.support.v4.widget.DrawerLayout>

fragment_main.xml

<RelativeLayout 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=".main$PlaceholderFragment">

</RelativeLayout>

fragment_navigation_drawer.xml

<ListView 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:choiceMode="singleChoice"
    android:divider="@android:color/transparent"
    android:dividerHeight="0dp"
    android:background="#000"
    tools:context=".NavigationDrawerFragment" />

在我能夠為您進行一些調整之前,從與您一起使用此應用程序開始。

要做的是將新的Views添加到fragment_navigation_drawer.xml並更改NavigationDrawerFragment以匹配並包括所做的更改。

布局

<?xml version="1.0" encoding="utf-8"?>
<!-- the root view is now a LinearLayout, all other Views are children of this -->
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_height="match_parent"
    android:layout_width="match_parent"
    android:background="#cccc"
    android:orientation="vertical">

    <!-- a separate section to go above the list -->
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:padding="10dp"
        android:orientation="horizontal">

        <!-- your image, you can set it later (see NavDrawerFrag) -->
        <ImageView
            android:id="@+id/nav_image"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:padding="15dp"
            android:src="@android:drawable/ic_menu_myplaces"/>

        <!-- a bit of test or a title to go with it -->
        <TextView
            android:id="@+id/nav_text"
            android:layout_width="0dp"
            android:layout_weight="1"
            android:layout_height="match_parent"
            android:gravity="center_vertical"
            android:text="Default text"/>

    </LinearLayout>

    <!-- some divider thing -->
    <View
        android:layout_width="match_parent"
        android:layout_height="2dp"
        android:padding="20dp"
        android:background="#000000"/>

    <!-- your ListView is now a child View -->
    <ListView
        android:id="@+id/nav_listView"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:choiceMode="singleChoice"
        android:divider="@android:color/transparent"
        android:dividerHeight="0dp"/>

</LinearLayout>

分段

// new class level members
private ImageView mDrawerImage;
private TextView mDrawerText;

// change the View inflation and extract the new child views
// also modifying the ListView to now be a child instead of the root View
@Override
public View onCreateView(LayoutInflater inflater,
                         ViewGroup container,
                         Bundle savedInstanceState)
{
    // need site names for list
    siteNames = getActivity().getResources().getStringArray(R.array.site_names);
    Log.d(TAG, "number of sites loaded: " + siteNames.length);

    // inflate the parent view (the entire layout)
    View view = inflater.inflate(R.layout.fragment_navigation_drawer, container, false);
    // now grab the separate child views from inside it
    mDrawerListView = (ListView) view.findViewById(R.id.nav_listView);
    mDrawerImage = (ImageView) view.findViewById(R.id.nav_image);
    mDrawerText = (TextView) view.findViewById(R.id.nav_text);

    // configure the Views
    mDrawerText.setText("Give it a name/title");
    //mDrawerImage.setImageURI(...);    // set your ImageView however you want, I just gave it one in XML
    mDrawerListView.setOnItemClickListener(this);
    mDrawerListView.setAdapter(new ArrayAdapter<String>(getActionBar().getThemedContext(),
            android.R.layout.simple_list_item_1, android.R.id.text1, siteNames));
    mDrawerListView.setItemChecked(mCurrentSelectedPosition, true);

    // and return the inflated view up the stack
    return view;
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM