您好我是Android开发的新手,我在使用导航抽屉的片段中的listview中显示联系人列表时遇到问题
列表实际上正在运行,但它打开了"新窗口"而不是在碎片内部
抱歉我的英文不好在我的src文件夹中我有: - MainActivity.java - HomeFragment.java - FindPeopleFragment.java - ContactsActivity.java .....
在我的布局文件夹中我有: - activity_main.xml - fragment_home.xml - fragment_find_people.xml - lv_layout.xml .....
代码:
MainActivity.java;
import info.of.slidingmenu.adapter.NavDrawerListAdapter;
import info.of.slidingmenu.model.NavDrawerItem;
import java.io.File;
import java.io.FileOutputStream;
import java.util.ArrayList;
import android.app.Activity;
import android.app.Fragment;
import android.app.FragmentManager;
import android.content.Intent;
import android.content.res.Configuration;
import android.content.res.TypedArray;
import android.database.Cursor;
import android.database.MatrixCursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.support.v4.app.ActionBarDrawerToggle;
import android.support.v4.app.FragmentActivity;
import android.support.v4.widget.DrawerLayout;
import android.support.v4.widget.SimpleCursorAdapter;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.Toast;
public class MainActivity extends Activity {
private DrawerLayout mDrawerLayout;
private ListView mDrawerList;
private ActionBarDrawerToggle mDrawerToggle;
// nav drawer title
private CharSequence mDrawerTitle;
// used to store app title
private CharSequence mTitle;
// slide menu items
private String[] navMenuTitles;
private TypedArray navMenuIcons;
private ArrayList<NavDrawerItem> navDrawerItems;
private NavDrawerListAdapter adapter;
SimpleCursorAdapter mAdapter;
MatrixCursor mMatrixCursor;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mTitle = mDrawerTitle = getTitle();
// load slide menu items
navMenuTitles = getResources().getStringArray(R.array.nav_drawer_items);
// nav drawer icons from resources
navMenuIcons = getResources()
.obtainTypedArray(R.array.nav_drawer_icons);
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
mDrawerList = (ListView) findViewById(R.id.list_slidermenu);
navDrawerItems = new ArrayList<NavDrawerItem>();
// adding nav drawer items to array
// Home
navDrawerItems.add(new NavDrawerItem(navMenuTitles[0], navMenuIcons.getResourceId(0, -1)));
// Find People
navDrawerItems.add(new NavDrawerItem(navMenuTitles[1], navMenuIcons.getResourceId(1, -1)));
// Photos
navDrawerItems.add(new NavDrawerItem(navMenuTitles[2], navMenuIcons.getResourceId(2, -1)));
// Communities, Will add a counter here
navDrawerItems.add(new NavDrawerItem(navMenuTitles[3], navMenuIcons.getResourceId(3, -1), true, "22"));
// Pages
navDrawerItems.add(new NavDrawerItem(navMenuTitles[4], navMenuIcons.getResourceId(4, -1)));
// What's hot, We will add a counter here
navDrawerItems.add(new NavDrawerItem(navMenuTitles[5], navMenuIcons.getResourceId(5, -1), true, "50+"));
// Recycle the typed array
navMenuIcons.recycle();
mDrawerList.setOnItemClickListener(new SlideMenuClickListener());
// setting the nav drawer list adapter
adapter = new NavDrawerListAdapter(getApplicationContext(),
navDrawerItems);
mDrawerList.setAdapter(adapter);
// enabling action bar app icon and behaving it as toggle button
getActionBar().setDisplayHomeAsUpEnabled(true);
getActionBar().setHomeButtonEnabled(true);
mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout,
R.drawable.ic_drawer, //nav menu toggle icon
R.string.app_name, // nav drawer open - description for accessibility
R.string.app_name // nav drawer close - description for accessibility
) {
public void onDrawerClosed(View view) {
getActionBar().setTitle(mTitle);
// calling onPrepareOptionsMenu() to show action bar icons
invalidateOptionsMenu();
}
public void onDrawerOpened(View drawerView) {
getActionBar().setTitle(mDrawerTitle);
// calling onPrepareOptionsMenu() to hide action bar icons
invalidateOptionsMenu();
}
};
mDrawerLayout.setDrawerListener(mDrawerToggle);
if (savedInstanceState == null) {
// on first time display view for first nav item
displayView(0);
}
Toast.makeText(this, "Activity created", Toast.LENGTH_LONG).show();
}
String[] prefix = new String[]{"0610","0611","0613","0615","0616","0618","0622","0623",
"0624","0628","0641","0642","0648","0650","0651","0652",
"0653","0654","0655","0658","0659","0661","0662","0666",
"0667","0668","0670","0671","0672","0673","0676","0677",
"0678"," ","0612","0614","0617","0619","0620","0644","0645",
"0649","0656","0657","0660","0663","0664","0665","0669","0674"
,"0675","0679"," ","0600","0601","0602","0603","0606","0626",
"0627","0629","0630","0633","0634","0635","0638","0699"," ",
"0640","0646","0647"," ","0526","0527","0540","0546","0547",
"0533","0534","0550","0553"};
String[] provider = new String[]{"iam","meditel","inwi","modem_inwi","bayn"};
public String getProvider(String num){
//0642212125
//+212642848
String ns;
String msg = "";
if(num.indexOf("+") != -1){
ns = "0" +num.substring(4, 7);
}else{
ns = num.substring(0,4);
}
int j = 0;
boolean found = false;
for (int i = 0; i < prefix.length-1; i++) {
if(prefix[i].equals(ns) & found == false){
msg = provider[j] ;
found = true;
if (msg == "inwi"){
ImageView Imgview = (ImageView) findViewById(R.id.imgViewOperator2);
Imgview.setImageResource(R.drawable.inwi);
}
else if (msg == "meditel"){
ImageView Imgview = (ImageView) findViewById(R.id.imgViewOperator2);
Imgview.setImageResource(R.drawable.meditel);
}
else if (msg == "bayn"){
ImageView Imgview = (ImageView) findViewById(R.id.imgViewOperator2);
Imgview.setImageResource(R.drawable.bayn);
}
else if (msg == "iam"){
ImageView Imgview = (ImageView) findViewById(R.id.imgViewOperator2);
Imgview.setImageResource(R.drawable.iam);
}
else if (msg == "modem_inwi"){
ImageView Imgview = (ImageView) findViewById(R.id.imgViewOperator2);
Imgview.setImageResource(R.drawable.modem_inwi);
}
else{
ImageView Imgview = (ImageView) findViewById(R.id.imgViewOperator2);
Imgview.setImageResource(R.drawable.none);
}
//document.getElementById("src_img").innerHTML = "<img src='images/puces/" + provider[j] + ".png' alt='' />";
// break;
}
else if(prefix[i] == " " & found == false){
j += 1;
// msg = j + " " + ns + " " + provider[j];
}
else if(i == prefix.length & found == false){
msg = "";
//document.getElementById("src_img").innerHTML = "<img src='images/puces/none.png' alt='' />";
}
};
return msg;
}
/**
* Slide menu item click listener
* */
private class SlideMenuClickListener implements
ListView.OnItemClickListener {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
// display view for selected nav drawer item
displayView(position);
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// toggle nav drawer on selecting action bar app icon/title
if (mDrawerToggle.onOptionsItemSelected(item)) {
return true;
}
// Handle action bar actions click
switch (item.getItemId()) {
case R.id.action_settings:
return true;
default:
return super.onOptionsItemSelected(item);
}
}
/* *
* Called when invalidateOptionsMenu() is triggered
*/
@Override
public boolean onPrepareOptionsMenu(Menu menu) {
// if nav drawer is opened, hide the action items
boolean drawerOpen = mDrawerLayout.isDrawerOpen(mDrawerList);
menu.findItem(R.id.action_settings).setVisible(!drawerOpen);
return super.onPrepareOptionsMenu(menu);
}
/**
* Diplaying fragment view for selected nav drawer list item
* */
private void displayView(int position) {
// update the main content by replacing fragments
Fragment fragment = null;
switch (position) {
case 0:
fragment = new HomeFragment();
break;
case 1:
fragment = new FindPeopleFragment();
break;
case 2:
fragment = new PhotosFragment();
break;
case 3:
fragment = new CommunityFragment();
break;
case 4:
fragment = new PagesFragment();
break;
case 5:
fragment = new WhatsHotFragment();
break;
default:
break;
}
if (fragment != null) {
FragmentManager fragmentManager = getFragmentManager();
fragmentManager.beginTransaction()
.replace(R.id.frame_container, fragment).commit();
// update selected item and title, then close the drawer
mDrawerList.setItemChecked(position, true);
mDrawerList.setSelection(position);
setTitle(navMenuTitles[position]);
mDrawerLayout.closeDrawer(mDrawerList);
Toast.makeText(this, "mDrawerList Position: " + position, Toast.LENGTH_LONG).show();
} else {
// error in creating fragment
Log.e("MainActivity", "Error in creating fragment");
}
}
@Override
public void setTitle(CharSequence title) {
mTitle = title;
getActionBar().setTitle(mTitle);
}
/**
* When using the ActionBarDrawerToggle, you must call it during
* onPostCreate() and onConfigurationChanged()...
*/
@Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
// Sync the toggle state after onRestoreInstanceState has occurred.
mDrawerToggle.syncState();
}
@Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
// Pass any configuration change to the drawer toggls
mDrawerToggle.onConfigurationChanged(newConfig);
}
}
activity_main.xml中:
<android.support.v4.widget.DrawerLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent">
<!-- Framelayout to display Fragments -->
<FrameLayout
android:id="@+id/frame_container"
android:layout_width="match_parent"
android:layout_height="match_parent" />
<!-- Listview to display slider menu -->
<ListView
android:id="@+id/list_slidermenu"
android:layout_width="240dp"
android:layout_height="match_parent"
android:layout_gravity="start"
android:choiceMode="singleChoice"
android:divider="@color/list_divider"
android:dividerHeight="0dp"
android:listSelector="@drawable/list_selector"
android:background="@color/list_background"/>
</android.support.v4.widget.DrawerLayout>
FindPeopleFragment.java:
import android.app.Fragment;
import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ListView;
public class FindPeopleFragment extends Fragment {
public FindPeopleFragment(){}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_find_people, container, false);
Intent myIntent = new Intent((MainActivity)getActivity(), ContactsActivity.class);
getActivity().startActivity(myIntent);
return rootView;
}
}
fragment_find_people.xml:
<?xml version="1.0" encoding="utf-8"?>
<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" >
<ListView
android:id="@+id/listview"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</RelativeLayout>
ContactsActivity.java:
import java.io.File;
import java.io.FileOutputStream;
import android.app.Activity;
import android.database.Cursor;
import android.database.MatrixCursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.support.v4.app.FragmentActivity;
import android.support.v4.widget.SimpleCursorAdapter;
import android.view.Menu;
import android.view.View;
import android.widget.ListView;
public class ContactsActivity extends Activity {
SimpleCursorAdapter mAdapter;
MatrixCursor mMatrixCursor;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.fragment_find_people);
// The contacts from the contacts content provider is stored in this cursor
mMatrixCursor = new MatrixCursor(new String[] { "_id","name","photo","details"} );
// Adapter to set data in the listview
mAdapter = new SimpleCursorAdapter(getBaseContext(),
R.layout.lv_layout,
null,
new String[] { "name","photo","details"},
new int[] { R.id.tv_name,R.id.iv_photo,R.id.tv_details}, 0);
// Getting reference to listview
ListView lstContacts = (ListView) findViewById(R.id.listview);
// Setting the adapter to listview
lstContacts.setAdapter(mAdapter);
// Creating an AsyncTask object to retrieve and load listview with contacts
ListViewContactsLoader listViewContactsLoader = new ListViewContactsLoader();
// Starting the AsyncTask process to retrieve and load listview with contacts
listViewContactsLoader.execute();
}
/** An AsyncTask class to retrieve and load listview with contacts */
private class ListViewContactsLoader extends AsyncTask<Void, Void, Cursor>{
@Override
protected Cursor doInBackground(Void... params) {
Uri contactsUri = ContactsContract.Contacts.CONTENT_URI;
// Querying the table ContactsContract.Contacts to retrieve all the contacts
Cursor contactsCursor = getContentResolver().query(contactsUri, null, null, null,
ContactsContract.Contacts.DISPLAY_NAME + " ASC ");
if(contactsCursor.moveToFirst()){
do{
long contactId = contactsCursor.getLong(contactsCursor.getColumnIndex("_ID"));
Uri dataUri = ContactsContract.Data.CONTENT_URI;
// Querying the table ContactsContract.Data to retrieve individual items like
// home phone, mobile phone, work email etc corresponding to each contact
Cursor dataCursor = getContentResolver().query(dataUri, null,
ContactsContract.Data.CONTACT_ID + "=" + contactId,
null, null);
String displayName="";
String nickName="";
String homePhone="";
String mobilePhone="";
String workPhone="";
String otherPhone="";
String photoPath="" + R.drawable.blank;
byte[] photoByte=null;
String homeEmail="";
String workEmail="";
String companyName="";
String title="";
if(dataCursor.moveToFirst()){
// Getting Display Name
displayName = dataCursor.getString(dataCursor.getColumnIndex(ContactsContract.Data.DISPLAY_NAME ));
do{
// Getting NickName
if(dataCursor.getString(dataCursor.getColumnIndex("mimetype")).equals(ContactsContract.CommonDataKinds.Nickname.CONTENT_ITEM_TYPE))
nickName = dataCursor.getString(dataCursor.getColumnIndex("data1"));
// Getting Phone numbers
if(dataCursor.getString(dataCursor.getColumnIndex("mimetype")).equals(ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE)){
switch(dataCursor.getInt(dataCursor.getColumnIndex("data2"))){
case ContactsContract.CommonDataKinds.Phone.TYPE_HOME :
homePhone = dataCursor.getString(dataCursor.getColumnIndex("data1"));
break;
case ContactsContract.CommonDataKinds.Phone.TYPE_MOBILE :
mobilePhone = dataCursor.getString(dataCursor.getColumnIndex("data1"));
break;
case ContactsContract.CommonDataKinds.Phone.TYPE_WORK :
workPhone = dataCursor.getString(dataCursor.getColumnIndex("data1"));
break;
case ContactsContract.CommonDataKinds.Phone.TYPE_OTHER :
otherPhone = dataCursor.getString(dataCursor.getColumnIndex("data1"));
break;
}
}
// Getting EMails
if(dataCursor.getString(dataCursor.getColumnIndex("mimetype")).equals(ContactsContract.CommonDataKinds.Email.CONTENT_ITEM_TYPE ) ) {
switch(dataCursor.getInt(dataCursor.getColumnIndex("data2"))){
case ContactsContract.CommonDataKinds.Email.TYPE_HOME :
homeEmail = dataCursor.getString(dataCursor.getColumnIndex("data1"));
break;
case ContactsContract.CommonDataKinds.Email.TYPE_WORK :
workEmail = dataCursor.getString(dataCursor.getColumnIndex("data1"));
break;
}
}
// Getting Organization details
if(dataCursor.getString(dataCursor.getColumnIndex("mimetype")).equals(ContactsContract.CommonDataKinds.Organization.CONTENT_ITEM_TYPE)){
companyName = dataCursor.getString(dataCursor.getColumnIndex("data1"));
title = dataCursor.getString(dataCursor.getColumnIndex("data4"));
}
// Getting Photo
if(dataCursor.getString(dataCursor.getColumnIndex("mimetype")).equals(ContactsContract.CommonDataKinds.Photo.CONTENT_ITEM_TYPE)){
photoByte = dataCursor.getBlob(dataCursor.getColumnIndex("data15"));
if(photoByte != null) {
Bitmap bitmap = BitmapFactory.decodeByteArray(photoByte, 0, photoByte.length);
// Getting Caching directory
File cacheDirectory = getBaseContext().getCacheDir();
// Temporary file to store the contact image
File tmpFile = new File(cacheDirectory.getPath() + "/wpta_"+contactId+".png");
// The FileOutputStream to the temporary file
try {
FileOutputStream fOutStream = new FileOutputStream(tmpFile);
// Writing the bitmap to the temporary file as png file
bitmap.compress(Bitmap.CompressFormat.PNG,100, fOutStream);
// Flush the FileOutputStream
fOutStream.flush();
//Close the FileOutputStream
fOutStream.close();
} catch (Exception e) {
e.printStackTrace();
}
photoPath = tmpFile.getPath();
}
}
}while(dataCursor.moveToNext());
String details = "";
// Concatenating various information to single string
if(homePhone != null && !homePhone.equals("") )
details = "HomePhone : " + homePhone + "\n";
if(mobilePhone != null && !mobilePhone.equals("") )
details += "MobilePhone : " + mobilePhone + "\n";
if(workPhone != null && !workPhone.equals("") )
details += "WorkPhone : " + workPhone + "\n";
if(otherPhone != null && !otherPhone.equals("") )
details += "OtherPhone : " + otherPhone + "\n";
if(nickName != null && !nickName.equals("") )
details += "NickName : " + nickName + "\n";
if(homeEmail != null && !homeEmail.equals("") )
details += "HomeEmail : " + homeEmail + "\n";
if(workEmail != null && !workEmail.equals("") )
details += "WorkEmail : " + workEmail + "\n";
if(companyName != null && !companyName.equals("") )
details += "CompanyName : " + companyName + "\n";
if(title != null && !title.equals("") )
details += "Title : " + title + "\n";
// Adding id, display name, path to photo and other details to cursor
mMatrixCursor.addRow(new Object[]{ Long.toString(contactId),displayName,photoPath,details});
}
}while(contactsCursor.moveToNext());
}
return mMatrixCursor;
}
@Override
protected void onPostExecute(Cursor result) {
// Setting the cursor containing contacts to listview
mAdapter.swapCursor(result);
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
lv_layout.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="horizontal" >
<ImageView
android:id="@+id/iv_photo"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="10dp" />
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical" >
<TextView
android:id="@+id/tv_name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="4dp"
android:textSize="15sp" />
<TextView
android:id="@+id/tv_details"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="4dp"
android:textSize="12sp" />
</LinearLayout>
</LinearLayout>
的AndroidManifest.xml:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="info.of.slidingmenu"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="11"
android:targetSdkVersion="17" />
<uses-permission android:name="android.permission.READ_CONTACTS"/>
<uses-permission android:name="android.permission.READ_PHONE_STATE"/>
<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/CustomActionBarTheme" android:logo="@drawable/logo">
<activity
android:name="info.of.slidingmenu.MainActivity"
android:label="@string/app_name"
android:configChanges="orientation|screenSize">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name="info.of.slidingmenu.ContactsActivity"
android:label="@string/app_name"
android:configChanges="orientation|screenSize">
</activity>
</application>
</manifest>
任何帮助请!!
答案 0 :(得分:0)
问题在于您的FindPeopleFragment
,您从Activity
开始onCreateView
,而应该设置Fragment layout
并在Fragment
中执行其他处理}
将所有代码从ContactsActivity
移至FindPeopleFragment
。您可以在膨胀视图中找到Fragment布局中的视图,如下所示
// Getting reference to listview
ListView lstContacts = (ListView) rootView .findViewById(R.id.listview);
更改onCreateView
的{{1}}并执行所有其他操作
FindPeopleFragment