gpt4 book ai didi

java - 如何将大个人资料图片添加到我的抽屉导航中?

转载 作者:行者123 更新时间:2023-12-01 12:49:18 24 4
gpt4 key购买 nike

所以,几天前我开始开发我的第一个应用程序。这是一个带有抽屉导航的应用程序,用户可以设置一些网站快捷方式以显示在抽屉导航中。如果用户单击网站,它将在 WebView 中打开。确实没什么特别的,但这是我为了训练我的 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" />

最佳答案

在我能够为您进行一些调整之前,我曾与您一起开发此应用程序。

必须做的是将新 View 添加到 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>

fragment

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

关于java - 如何将大个人资料图片添加到我的抽屉导航中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24370760/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com