【问题标题】:how to switch from a fragment in a fragmentActivity to the Activity in android如何从fragmentActivity中的一个fragment切换到android中的Activity
【发布时间】:2014-12-07 16:30:44
【问题描述】:

我有一个片段类,其中有几个片段选项卡。他们每个人都在打开另一个专用片段。但我想更改一个片段以打开一个活动类。我经历了很多例子,但问题没有解决。每次我的应用程序崩溃。

这是我的片段类。

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.NameValuePair;

import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.graphics.Typeface;
import android.os.AsyncTask;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.appdupe.flamer.LoginUsingFacebook;
import com.appdupe.flamer.LoginUsingFacebook.BackGroundTaskForFetchingDataFromFaceBook;

import com.actionbarsherlock.app.SherlockFragmentActivity;
import com.androidquery.AQuery;
import com.androidquery.callback.ImageOptions;
import com.appdupe.androidpushnotifications.ChatActivity;
import com.appdupe.flamer.QuestionsActivity;
import com.appdupe.flamer.pojo.LikeMatcheddataForListview;
import com.appdupe.flamer.pojo.LikedMatcheData;
import com.appdupe.flamer.pojo.Likes;
import com.appdupe.flamer.utility.AlertDialogManager;
import com.appdupe.flamer.utility.AppLog;
import com.appdupe.flamer.utility.ConnectionDetector;
import com.appdupe.flamer.utility.Constant;
import com.appdupe.flamer.utility.ScalingUtilities;
import com.appdupe.flamer.utility.ScalingUtilities.ScalingLogic;
import com.appdupe.flamer.utility.SessionManager;
import com.appdupe.flamer.utility.Ultilities;
import com.appdupe.flamer.utility.Utility;
import com.appdupe.flamerchat.db.DatabaseHandler;
import com.appdupe.flamernofb.R;
import com.google.gson.Gson;
import com.jeremyfeinstein.slidingmenu.lib.SlidingMenu;
import com.jeremyfeinstein.slidingmenu.lib.SlidingMenu.OnOpenListener;

public class MainActivity extends SherlockFragmentActivity implements
        OnClickListener, OnOpenListener {
    // MainLayout mLayout;
    private static final String TAG = "MainActivity";
    private ListView matcheslistview;
    Button btMenu;
    private Button buttonRightMenu;
    TextView tvTitle;
    private Typeface topbartextviewFont;
    private Editor editor;
    private SharedPreferences preferences;
    private EditText etSerchFriend;
    double mLatitude = 0;
    double mLongitude = 0;
    double dLatitude = 0;
    double dLongitude = 0;
    // private Session.StatusCallback statusCallback = new
    // SessionStatusCallback();
    private Dialog mdialog;
    // private boolean usersignup = false;
    private boolean isProfileclicked = false;
    private ArrayList<LikeMatcheddataForListview> arryList;
    private MatchedDataAdapter adapter;
    private ImageView profileimage;
    private LinearLayout profilelayout, homelayout, messages, settinglayout,
            invitelayout, questionLayout;
    public SlidingMenu menu;
    private boolean flagforHome, flagForProfile, flagForsetting;
    // private AQuery aQuery;
    private ImageOptions options;
    private ConnectionDetector cd;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // mLayout = (MainLayout)
        // this.getLayoutInflater().inflate(R.layout.slidmenuxamplemainactivity,
        // null);
        // setContentView(mLayout);
        cd = new ConnectionDetector(this);
        preferences = PreferenceManager.getDefaultSharedPreferences(this);
        editor = preferences.edit();
        // aQuery = new AQuery(this);
        options = new ImageOptions();
        options.fileCache = true;
        options.memCache = true;
        setContentView(R.layout.slidmenuxamplemainactivity);

        if (preferences.getBoolean(Constant.PREF_ISFIRST, true)) {
            editor.putBoolean(Constant.PREF_ISFIRST, false);
            editor.commit();
            //startActivity(new Intent(this, QuestionsActivity.class));
        }
        tvTitle = (TextView) findViewById(R.id.activity_main_content_title);
        topbartextviewFont = Typeface.createFromAsset(getAssets(),
                "fonts/HelveticaLTStd-Light.otf");
        tvTitle.setTypeface(topbartextviewFont);
        tvTitle.setTextColor(Color.rgb(255, 255, 255));
        tvTitle.setTextSize(20);
        menu = new SlidingMenu(this);
        menu.setMode(SlidingMenu.LEFT_RIGHT);
        menu.setTouchModeAbove(SlidingMenu.TOUCHMODE_MARGIN);
        menu.setShadowWidthRes(R.dimen.shadow_width);
        menu.setShadowDrawable(R.drawable.shadow);
        menu.setBehindOffsetRes(R.dimen.slidingmenu_offset);
        menu.setFadeDegree(0.35f);
        menu.attachToActivity(this, SlidingMenu.SLIDING_CONTENT);
        Log.d(TAG, "onCreate  before add menu ");
        menu.setMenu(R.layout.leftmenu);
        menu.setSecondaryMenu(R.layout.rightmenu);
        Log.d(TAG, "onCreate  add menu ");
        menu.setSlidingEnabled(true);
        Log.d(TAG, "onCreate  finish");

        // search
        etSerchFriend = (EditText) menu
                .findViewById(R.id.et_serch_right_side_menu);

        // btnSerch = (Button) menu.findViewById(R.id.btn_serch_right_side);

        View leftmenuview = menu.getMenu();
        View rightmenuview = menu.getSecondaryMenu();

        initLayoutComponent(leftmenuview, rightmenuview);

        menu.setSecondaryOnOpenListner(this);

        // lvMenuItems = getResources().getStringArray(R.array.menu_items);

        // lvMenu.setAdapter(new
        // ArrayAdapter<String>(this,android.R.layout.simple_list_item_1,
        // lvMenuItems));

        matcheslistview.setOnItemClickListener(new OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
                    long arg3) {
                // logDebug("setOnItemClickListener  onItemClick arg2 "+arg2);

                LikeMatcheddataForListview matcheddataForListview = (LikeMatcheddataForListview) arg0
                        .getItemAtPosition(arg2);
                String faceboolid = matcheddataForListview.getFacebookid();
                // logDebug(" background setOnItemClickListener  onItemClick friend facebook id faceboolid "+faceboolid);
                // logDebug(" background setOnItemClickListener  onItemClick user facebook id  faceboolid"+new
                // SessionManager(MainActivity.this).getFacebookId());
                Bundle mBundle = new Bundle();
                mBundle.putString(Constant.FRIENDFACEBOOKID, faceboolid);
                mBundle.putString(Constant.CHECK_FOR_PUSH_OR_NOT, "1");

                Intent mIntent = new Intent(MainActivity.this,
                        ChatActivity.class);
                mIntent.putExtras(mBundle);
                startActivity(mIntent);
                menu.toggle();

            }
        });

        buttonRightMenu = (Button) findViewById(R.id.button_right_menu);

        btMenu = (Button) findViewById(R.id.button_menu);
        btMenu.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                // Show/hide the menu
                toggleMenu(v);
            }
        });

        try {

            profilelayout.setOnClickListener(this);
            homelayout.setOnClickListener(this);
            messages.setOnClickListener(this);
            settinglayout.setOnClickListener(this);
            invitelayout.setOnClickListener(this);
            questionLayout.setOnClickListener(this);

        } catch (Exception e) {
            AppLog.handleException("oncreate   Exception  ", e);
        }

        // Bundle extras = getIntent().getExtras();
        System.out.println("Get Intent done");
        try {
            FragmentManager fm = MainActivity.this.getSupportFragmentManager();
            FragmentTransaction ft = fm.beginTransaction();
            FindMatches fragment = new FindMatches();
            ft.add(R.id.activity_main_content_fragment, fragment);
            tvTitle.setText(getResources().getString(R.string.app_name));

            ft.commit();
            setProfilePick(profileimage);

        } catch (Exception e) {
            AppLog.handleException("onCreate Exception ", e);

        }

        Ultilities mUltilities = new Ultilities();
        int imageHeightAndWidht[] = mUltilities
                .getImageHeightAndWidthForAlubumListview(this);
        arryList = new ArrayList<LikeMatcheddataForListview>();
        adapter = new MatchedDataAdapter(this, arryList, imageHeightAndWidht);
        matcheslistview.setAdapter(adapter);

        // final SessionManager sessionManager = new SessionManager(this);

        buttonRightMenu.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                if (isProfileclicked) {
                    Intent mIntent = new Intent(MainActivity.this,
                            EditProfileNew.class);
                    startActivity(mIntent);
                } else {
                    toggleRightMenu(v);



                }

            }
        });

        initSerchData();

    }




    private void initSerchData() {
        etSerchFriend.addTextChangedListener(new TextWatcher() {

            @Override
            public void onTextChanged(CharSequence s, int start, int before,
                    int count) {
                adapter.getFilter().filter(s.toString().trim());
            }

            @Override
            public void beforeTextChanged(CharSequence s, int start, int count,
                    int after) {
            }

            @Override
            public void afterTextChanged(Editable s) {
            }
        });
    }

    public void setMenuTouchFullScreenEnable(boolean isEnable) {
        if (isEnable) {
            menu.setTouchModeAbove(SlidingMenu.TOUCHMODE_FULLSCREEN);
        } else {
            menu.setTouchModeAbove(SlidingMenu.TOUCHMODE_NONE);
        }
    }

    @Override
    public void onOpen() {
        AppLog.Log(TAG, "onOpen");
        findLikedMatched();
    }

    @Override
    protected void onResume() {
        super.onResume();
        AppLog.Log(TAG, " MainActivity   onResume  called");

    }

    private void setProfilePick(final ImageView userProfilImage) {
        final Ultilities mUltilities = new Ultilities();


        new Thread(new Runnable() {

            @Override
            public void run() {
                final Bitmap bitmapimage = Utility.getBitmapFromURL(preferences
                        .getString(Constant.PREF_PROFILE_IMAGE_ONE, ""));
                runOnUiThread(new Runnable() {

                    @Override
                    public void run() {
                        AppLog.Log(
                                TAG,
                                "Profile Image Url:"
                                        + preferences
                                                .getString(
                                                        Constant.PREF_PROFILE_IMAGE_ONE,
                                                        ""));
                        Bitmap cropedBitmap = null;
                        ScalingUtilities mScalingUtilities = new ScalingUtilities();
                        Bitmap mBitmap = null;
                        if (bitmapimage != null) {
                            cropedBitmap = mScalingUtilities
                                    .createScaledBitmap(bitmapimage, 80, 80,
                                            ScalingLogic.CROP);
                            bitmapimage.recycle();
                            mBitmap = mUltilities.getCircleBitmap(cropedBitmap,
                                    1);
                            cropedBitmap.recycle();
                            userProfilImage.setImageBitmap(mBitmap);
                            // aQuery.id(userProfilImage).image(mBitmap);
                        } else {
                        }

                    }
                });

            }
        }).start();


    }

    private void initLayoutComponent(View leftmenu, View rightmenu) {

        matcheslistview = (ListView) rightmenu
                .findViewById(R.id.menu_right_ListView);


        profileimage = (ImageView) leftmenu.findViewById(R.id.profileimage);


        profilelayout = (LinearLayout) leftmenu
                .findViewById(R.id.profilelayout);
        homelayout = (LinearLayout) leftmenu.findViewById(R.id.homelayout);
        messages = (LinearLayout) leftmenu.findViewById(R.id.messages);
        settinglayout = (LinearLayout) leftmenu
                .findViewById(R.id.settinglayout);
        invitelayout = (LinearLayout) leftmenu.findViewById(R.id.invitelayout);
        /*questionLayout = (LinearLayout) leftmenu
                .findViewById(R.id.questionLayout);*///devraj 


    }

    private void findLikedMatched() {

        AppLog.Log(TAG, "findLikedMatched");



        String params[] = { preferences.getString(Constant.FACEBOOK_ID, "") };
        new BackgroundTaskForFindLikeMatched().execute(params);

    }

    private class BackgroundTaskForFindLikeMatched extends
            AsyncTask<String, Void, Void> {
        private Ultilities mUltilities = new Ultilities();
        private List<NameValuePair> getuserparameter;
        private String likedmatchedata;
        private LikedMatcheData matcheData;
        private ArrayList<Likes> likesList;
        private LikeMatcheddataForListview matcheddataForListview;
        DatabaseHandler mDatabaseHandler = new DatabaseHandler(
                MainActivity.this);
        private boolean isResponseSuccess = true;

        @Override
        protected Void doInBackground(String... params) {
            try {

                File appDirectory = mUltilities
                        .createAppDirectoy(getResources().getString(
                                R.string.appdirectory));
                AppLog.Log(TAG,
                        "BackgroundTaskForFindLikeMatched   doInBackground appDirectory "
                                + appDirectory);
                File _picDir = new File(appDirectory, getResources().getString(
                        R.string.imagedirematchuserdirectory));

                AppLog.Log(TAG,
                        "BackgroundTaskForFindLikeMatched doInBackground ");

                getuserparameter = mUltilities.getUserLikedParameter(params);

                AppLog.Log(TAG,
                        "BackgroundTaskForFindLikeMatched doInBackground   getuserparameter "
                                + getuserparameter);

                likedmatchedata = mUltilities.makeHttpRequest(
                        Constant.getliked_url, Constant.methodeName,
                        getuserparameter);

                AppLog.Log(TAG,
                        "BackgroundTaskForFindLikeMatched doInBackground   likedmatchedata "
                                + likedmatchedata);

                Gson gson = new Gson();
                matcheData = gson.fromJson(likedmatchedata,
                        LikedMatcheData.class);

                AppLog.Log(TAG,
                        "BackgroundTaskForFindLikeMatched doInBackground   matcheData "
                                + matcheData);


                if (matcheData.getErrFlag() == 0) {
                    likesList = matcheData.getLikes();
                    AppLog.Log(TAG,
                            "BackgroundTaskForFindLikeMatched doInBackground   likesList "
                                    + likesList);
                    if (arryList != null) {
                        arryList.clear();
                    }

                    AppLog.Log(TAG,
                            "BackgroundTaskForFindLikeMatched doInBackground   likesList sized "
                                    + likesList.size());
                    for (int i = 0; i < likesList.size(); i++) {
                        matcheddataForListview = new LikeMatcheddataForListview();
                        String userName = likesList.get(i).getfName();
                        String facebookid = likesList.get(i).getFbId();

                        String picturl = likesList.get(i).getpPic();
                        int falg = likesList.get(i).getFlag();
                        String latd = likesList.get(i).getLadt();
                        matcheddataForListview.setFacebookid(facebookid);
                        matcheddataForListview.setUserName(userName);
                        matcheddataForListview.setImageUrl(picturl);
                        matcheddataForListview.setFlag("" + falg);
                        matcheddataForListview.setladt(latd);

                        File imageFile = mUltilities.createFileInSideDirectory(
                                _picDir, userName + facebookid + ".jpg");

                        Utility.addBitmapToSdCardFromURL(likesList.get(i)
                                .getpPic().replaceAll(" ", "%20"), imageFile);
                        matcheddataForListview.setFilePath(imageFile
                                .getAbsolutePath());
                        if (!preferences.getString(Constant.FACEBOOK_ID, "")
                                .equals(facebookid)) {
                            arryList.add(matcheddataForListview);
                        }

                    }
                    DatabaseHandler mDatabaseHandler = new DatabaseHandler(
                            MainActivity.this);


                    ArrayList<LikeMatcheddataForListview> arryListtem = mDatabaseHandler
                            .getUserFindMatch();
                    AppLog.Log(TAG, "arryListtem  " + arryListtem);
                    if (arryListtem != null && arryListtem.size() > 0) {
                        AppLog.Log(TAG, "arryList  size " + arryListtem.size());
                        arryList.clear();

                        arryList.addAll(arryListtem);
                        mUltilities.showImage
                    }

                }
                // "errNum": "50",
                // "errFlag": "1",
                // "errMsg": "Sorry, no matches found!"
                else if (matcheData.getErrFlag() == 1) {
                    ArrayList<LikeMatcheddataForListview> arryListtem = mDatabaseHandler
                            .getUserFindMatch();
                    AppLog.Log(TAG, "arryListtem  " + arryListtem);
                    if (arryListtem != null && arryListtem.size() > 0) {
                        AppLog.Log(TAG, "arryList  size " + arryListtem.size());
                        arryList.clear();

                        arryList.addAll(arryListtem);
                    }

                } else {

                }

            } catch (Exception e) {
                AppLog.handleException(
                        "BackgroundTaskForFindLikeMatched doInBackground Exception ",
                        e);

                isResponseSuccess = false;
            }
            return null;
        }

        @Override
        protected void onPostExecute(Void result) {
            super.onPostExecute(result);
            AppLog.Log(TAG, "BackgroundTaskForFindLikeMatched onPostExecute  ");
            try {
                mdialog.dismiss();
            } catch (Exception e) {
                AppLog.Log(TAG,
                        "BackgroundTaskForFindLikeMatched   onPostExecute  Exception "
                                + e);
            }
            if (!isResponseSuccess) {
                AlertDialogManager.errorMessage(MainActivity.this, "Alert",
                        "Request timeout");
            }
            adapter.notifyDataSetChanged();
        }

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            AppLog.Log(TAG, "BackgroundTaskForFindLikeMatched onPreExecute  ");
            try {
                mdialog = mUltilities.GetProcessDialog(MainActivity.this);
                mdialog.setCancelable(false);
                mdialog.show();
            } catch (Exception e) {
                AppLog.handleException(
                        "BackgroundTaskForFindLikeMatched   onPreExecute  Exception ",
                        e);
            }

        }

    }

    private class MatchedDataAdapter extends
            ArrayAdapter<LikeMatcheddataForListview> {
        private AQuery aQuery;
        private Activity mActivity;
        private LayoutInflater mInflater;
        private SessionManager sessionManager;

        public MatchedDataAdapter(Activity context,
                List<LikeMatcheddataForListview> objects,
                int imageHeigthAndWidth[]) {
            super(context, R.layout.matchedlistviewitem, objects);
            mActivity = context;
            mInflater = (LayoutInflater) mActivity
                    .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            // this.imageHeigthAndWidth=imageHeigthAndWidth;
            sessionManager = new SessionManager(context);
            aQuery = new AQuery(context);
        }

        @Override
        public int getCount() {
            return super.getCount();
        }

        @Override
        public LikeMatcheddataForListview getItem(int position) {
            return super.getItem(position);
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            ViewHolder holder;
            if (convertView == null) {
                holder = new ViewHolder();
                convertView = mInflater.inflate(R.layout.matchedlistviewitem,
                        null);
                holder.imageview = (ImageView) convertView
                        .findViewById(R.id.userimage);
                holder.textview = (TextView) convertView
                        .findViewById(R.id.userName);
                holder.lastMasage = (TextView) convertView
                        .findViewById(R.id.lastmessage);
                convertView.setTag(holder);
            } else {
                holder = (ViewHolder) convertView.getTag();
            }

            holder.textview.setId(position);
            holder.imageview.setId(position);
            holder.lastMasage.setId(position);
            holder.textview.setText(getItem(position).getUserName());
            aQuery.id(holder.imageview).image(getItem(position).getImageUrl());
            try {
                holder.lastMasage.setText(sessionManager
                        .getLastMessage(getItem(position).getFacebookid()));
            } catch (Exception e) {
                AppLog.handleException(TAG + " getView  Exception ", e);
            }

            return convertView;
        }

        class ViewHolder {
            ImageView imageview;
            TextView textview;
            TextView lastMasage;

        }
    }

    public void toggleMenu(View v) {
        menu.toggle();
    }

    public void toggleRightMenu(View v) {
        menu.showSecondaryMenu();
    }

    @Override
    public void onBackPressed() {
        if (menu.isMenuShowing()) {
            menu.toggle();
        } else if (menu.isSecondaryMenuShowing()) {
            menu.showSecondaryMenu();
        } else {
            super.onBackPressed();
        }
    }

    @Override
    public void onStop() {
        super.onStop();
        if (mdialog != null) {
            mdialog.dismiss();
            mdialog = null;
        }
    }

    @Override
    protected void onDestroy() {
        if (mdialog != null && mdialog.isShowing()) {
            mdialog.dismiss();
        }
        super.onDestroy();
    }

    @Override
    public void onClick(View v) {

        FragmentManager fm = MainActivity.this.getSupportFragmentManager();
        FragmentTransaction ft = fm.beginTransaction();
        Fragment fragment = null;

        if (v.getId() == R.id.homelayout) {
            if (!cd.isConnectingToInternet()) {
                Toast.makeText(this, "No Internet", Toast.LENGTH_SHORT).show();
                return;
            }
            if (flagforHome) {
                menu.toggle();
                return;
            } else {
                fragment = new FindMatches();
                buttonRightMenu
                        .setBackgroundResource(R.drawable.selector_for_message_button);
                tvTitle.setText(getResources().getString(R.string.app_name));
                flagforHome = true;
                flagForProfile = false;
                flagForsetting = false;

                isProfileclicked = false;
                if (fragment != null) {
                    ft.replace(R.id.activity_main_content_fragment, fragment);
                    ft.commit();

                }
                menu.toggle();
            }
        } else if (v.getId() == R.id.profilelayout) {
            if (!cd.isConnectingToInternet()) {
                Toast.makeText(this, "No Internet", Toast.LENGTH_SHORT).show();
                return;
            }
            if (flagForProfile) {
                menu.toggle();
                return;
            } else {
                buttonRightMenu.setBackgroundResource(R.drawable.edit_btn);
                isProfileclicked = true;

                fragment = new UserProfile();
                tvTitle.setText(getResources().getString(R.string.myprofile));
                flagforHome = false;
                flagForProfile = true;
                flagForsetting = false;

                if (fragment != null) {
                    ft.replace(R.id.activity_main_content_fragment, fragment);
                    ft.commit();

                }
                menu.toggle();
            }
        }

        else if (v.getId() == R.id.settinglayout) {
            if (!cd.isConnectingToInternet()) {
                Toast.makeText(this, "No Internet", Toast.LENGTH_SHORT).show();
                return;
            }
            if (flagForsetting) {
                menu.toggle();
                return;

            } else {
                buttonRightMenu
                        .setBackgroundResource(R.drawable.selector_for_message_button);
                tvTitle.setText(getResources().getString(R.string.settings));
                fragment = new SettingActivity();
                flagforHome = false;
                flagForProfile = false;
                flagForsetting = true;
                 flagForInvite=false;
                isProfileclicked = false;
                /*if (fragment != null) {
                    ft.replace(R.id.activity_main_content_fragment, fragment);
                    ft.commit();
                    // tvTitle.setText(selectedItem);
                }*/
                menu.toggle();
                /*Intent setIntent = new Intent(getApplicationContext(),Setting2.class);
                startActivity(setIntent);*/
            }
        }
        ///devraj
         else if (v.getId() == R.id.messages) {
            if (!cd.isConnectingToInternet()) {
                Toast.makeText(this, "No Internet", Toast.LENGTH_SHORT).show();
                return;
            }
            toggleRightMenu(v);

        } /*else if (v.getId() == R.id.questionLayout) {
            if (!cd.isConnectingToInternet()) {
                Toast.makeText(this, "No Internet", Toast.LENGTH_SHORT).show();
                return;*/
            /*}
            menu.toggle();
            Intent questionIntent = new Intent(this, QuestionsActivity.class);
            startActivity(questionIntent);*/

        //}
    else if (v.getId() == R.id.invitelayout) {
            if (!cd.isConnectingToInternet()) {
                Toast.makeText(this, "No Internet", Toast.LENGTH_SHORT).show();
                return;
            }
            // Change by Dilavar
            Intent sendIntent = new Intent();
            sendIntent.setAction(Intent.ACTION_SEND);
            sendIntent
                    .putExtra(
                            Intent.EXTRA_TEXT,
                            "I am using Flamer App ! Why don't you try it out...\nInstall Flamer now !\nhttps://play.google.com/store/apps/details?id=com.appdupe.flamernofb");
            sendIntent.putExtra(android.content.Intent.EXTRA_SUBJECT,
                    " Flamer App !");
            sendIntent.setType("message/rfc822"); //

            sendIntent.putExtra(android.content.Intent.EXTRA_EMAIL,
                    new String[] { " info@appdupe.com" });
            startActivity(Intent
                    .createChooser(sendIntent, "Send mail using..."));



        }

        /*settinglayout.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View arg0) {
                // TODO Auto-generated method stub

                Intent mintent = new Intent(getApplicationContext(),Setting2.class);
                startActivity(mintent);

            }
        });*/
    }

}

我希望 Setting 选项卡打开一个新的活动而不是 Setting2

的片段

这是我必须打开的活动课

导入android.app.Activity; 导入android.os.Bundle;

公共类 Setting2 扩展 Activity {

@Override
protected void onCreate(Bundle savedInstanceState) {
    // TODO Auto-generated method stub
    super.onCreate(savedInstanceState);
    setContentView(R.layout.setting2);

}

}

【问题讨论】:

  • 哇……没有答案……但是否定标记……那么否定标记先生,你能回答这个问题吗????或者你的工作是将问题标记为否定????
  • 您已经发布了启动该活动的代码: /*Intent setIntent = new Intent(getApplicationContext(),Setting2.class); startActivity(setIntent);*/ 这样有什么问题?
  • 我也没有投反对票,也发布了 logcat,但只有崩溃日志。
  • @NitinMisra 请检查我的 logcat 以及我的答案中的 xml 文件...
  • @tritop 应用程序崩溃...

标签: android android-activity android-fragments


【解决方案1】:

这是我的布局,我在这里发布了这么长时间,并且无权发布更多有问题的行。

    <?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" 
    >
<RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="#088A08" >

        <Button

            android:id="@+id/button_menu"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentLeft="true"
            android:layout_centerVertical="true"
            android:layout_marginLeft="10dp"
            android:background="@drawable/selector_for_menu_button"
            android:onClick="toggleMenu" />

        <TextView
            android:id="@+id/activity_main_content_title"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_centerHorizontal="true"
            android:layout_centerVertical="true"
            android:text="Toker" />

        <Button
            android:id="@+id/button_right_menu"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentRight="true"
            android:layout_centerVertical="true"
            android:layout_marginRight="10dp"
            android:background="@drawable/selector_for_message_button"
            android:onClick="rightmenu" />
    </RelativeLayout>

    <RelativeLayout
        android:layout_width="fill_parent"
        android:layout_height="150dp"
        android:background="#088A08" >

        <LinearLayout
            android:id="@+id/linearLayout1"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentTop="true"
            android:layout_centerHorizontal="true"
            android:background="#088A08" >

            <ImageView
                android:id="@+id/imagev1"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:background="@drawable/btn_add_photo"
                android:gravity="center_horizontal" />
        </LinearLayout>

        <Button
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_below="@+id/linearLayout1"
            android:layout_centerHorizontal="true"
            android:layout_marginTop="22dp"
            android:background="#088A08"
            android:gravity="center_horizontal"
            android:text="View My Profile" />

    </RelativeLayout>

    <LinearLayout 
        android:layout_width="fill_parent"
        android:layout_height="match_parent"
        android:orientation="vertical"
        android:weightSum="5.0">

        <RelativeLayout
            android:id="@+id/lin1"
            android:layout_width="fill_parent"

            android:layout_weight="1.0"
            android:background="#ffffff"
            android:orientation="horizontal" >

            <TextView
                android:id="@+id/textView1"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_alignBottom="@+id/imageView1"
                android:layout_alignTop="@+id/imageView1"
                android:layout_marginBottom="9dp"
                android:layout_marginLeft="21dp"
                android:layout_toRightOf="@+id/imageView1"
                android:text="Discovery Settings"
                android:textSize="12dp" />

            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_alignBottom="@+id/imageView1"
                android:layout_alignLeft="@+id/textView1"
                android:text="Change who you see" />

            <ImageView
                android:id="@+id/imageView1"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_alignParentLeft="true"
                android:layout_centerVertical="true"
                android:layout_marginLeft="12dp"
                android:background="@drawable/pref" />

            <Button
                android:id="@+id/morebtn1"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_alignParentRight="true"
                android:layout_alignTop="@+id/textView1"
                android:layout_marginRight="20dp"
                android:background="@drawable/more" />

        </RelativeLayout>

        <LinearLayout 
            android:layout_width="fill_parent"
            android:layout_height="1dp"

            android:background="@color/black"

            android:orientation="horizontal"/>

        <RelativeLayout
            android:layout_width="fill_parent"
            android:layout_weight="1.0"
            android:orientation="horizontal" >

            <ImageView
                android:id="@+id/imageView2"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_alignParentLeft="true"
                android:layout_centerVertical="true"
                android:layout_marginLeft="12dp"
                android:background="@drawable/settings" />

            <TextView
                android:id="@+id/textView3"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_alignTop="@+id/imageView2"
                android:layout_marginLeft="23dp"
                android:layout_toRightOf="@+id/imageView2"
                android:text="App Settings"
                android:textSize="12dp" />

            <TextView
                android:id="@+id/textView2"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_alignBottom="@+id/imageView2"
                android:layout_alignLeft="@+id/textView3"
                android:text="Notification and Resource" />

            <Button
                android:id="@+id/morebtn2"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_alignParentRight="true"
                android:layout_alignTop="@+id/textView3"
                android:layout_marginRight="20dp"
                android:background="@drawable/more" />

        </RelativeLayout>

        <LinearLayout 
            android:layout_width="fill_parent"
            android:layout_height="1dp"

            android:background="@color/black"

            android:orientation="horizontal"/>

        <RelativeLayout
            android:layout_width="fill_parent"
            android:layout_weight="1.0"
            android:orientation="horizontal" >

            <ImageView
                android:id="@+id/imageView3"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_alignParentLeft="true"
                android:layout_centerVertical="true"
                android:layout_marginLeft="12dp"
                android:background="@drawable/filter" />

            <TextView
                android:id="@+id/textView4"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_alignBottom="@+id/imageView3"
                android:layout_marginLeft="23dp"
                android:layout_toRightOf="@+id/imageView3"
                android:text="What are you into" />

            <TextView
                android:id="@+id/textView8"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_alignLeft="@+id/textView4"
                android:layout_alignTop="@+id/imageView3"
                android:text="Your Interest"
                android:textSize="12dp" />

            <Button
                android:id="@+id/morebtn3"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_alignParentRight="true"
                android:layout_alignTop="@+id/textView8"
                android:layout_marginRight="20dp"
                android:background="@drawable/more" />

        </RelativeLayout>

        <LinearLayout 
            android:layout_width="fill_parent"
            android:layout_height="1dp"

            android:background="@color/black"

            android:orientation="horizontal"/>

        <RelativeLayout
            android:layout_width="fill_parent"
            android:layout_weight="1.0"
            android:orientation="horizontal" >

            <ImageView
                android:id="@+id/imageView5"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_alignParentLeft="true"
                android:layout_centerVertical="true"
                android:layout_marginLeft="12dp"
                android:background="@drawable/reachout" />

            <TextView
                android:id="@+id/textView6"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_alignBottom="@+id/imageView5"
                android:layout_marginLeft="27dp"
                android:layout_toRightOf="@+id/imageView5"
                android:text="We want to hear it all" />

            <TextView
                android:id="@+id/textView7"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_alignLeft="@+id/textView6"
                android:layout_alignTop="@+id/imageView5"
                android:text="Get in Touch"
                android:textSize="12dp" />

            <Button
                android:id="@+id/morebtn4"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_alignParentRight="true"
                android:layout_alignTop="@+id/textView7"
                android:layout_marginRight="20dp"
                android:background="@drawable/more" />

        </RelativeLayout>

        <LinearLayout 
            android:layout_width="fill_parent"
            android:layout_height="1dp"
            android:background="@color/black"

            android:orientation="horizontal"/>

        <RelativeLayout
            android:layout_width="fill_parent"
            android:layout_weight="1.0"
            android:orientation="horizontal" >

            <ImageView
                android:id="@+id/imageView4"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_alignParentLeft="true"
                android:layout_centerVertical="true"
                android:layout_marginLeft="12dp"
                android:background="@drawable/share" />

            <Button
                android:id="@+id/morebtn5"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_alignParentRight="true"
                android:layout_alignTop="@+id/textView5"
                android:layout_marginRight="20dp"
                android:background="@drawable/more" />

            <TextView
                android:id="@+id/textView9"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_alignBottom="@+id/morebtn5"
                android:layout_marginLeft="27dp"
                android:layout_toRightOf="@+id/imageView4"
                android:text="Help us spread the world" />

            <TextView
                android:id="@+id/textView5"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_alignLeft="@+id/textView9"
                android:layout_alignTop="@+id/imageView4"
                android:text="Tell Your Friends"
                android:textSize="12dp" />

        </RelativeLayout>

        <LinearLayout 
            android:layout_width="fill_parent"
            android:layout_height="1dp"

            android:background="@color/black"

            android:orientation="horizontal"/>

    </LinearLayout>

    </LinearLayout>

【讨论】:

  • &lt;RelativeLayout android:id="@+id/lin1" android:layout_width="fill_parent" android:layout_weight="1.0" android:background="#ffffff" android:orientation="horizontal" &gt; add android:layout_height="wrap_content" 你应该避免这次崩溃
  • 您还错过了布局中多个位置的layout_height 属性,请将其添加到您的XML 中的每个ViewViewGroup
  • 你真的需要在任何地方设置高度。如果将其设置为 0,它不会影响重量。
  • 我确实尝试设置 layout_height 但它影响了我的布局设计..所以最后我删除了 layout_weight 并为所有布局设置了高度......它对我有用..
【解决方案2】:

第 1 步 - 在manifest
中声明您的活动 第 2 步
- starActivity(new Intent(getAcivity(), MyClass.class));
第 3 步
- 如果这没有帮助,请发布您的 logcat!
编辑:问题似乎是您没有为布局设置高度,根据您发布的布局,您有五个缺少android:layout_height 的布局,请添加并强制关闭将消失。

【讨论】:

  • 请看我发布的logcat ..它要求attibutes,但我已经描述了那里的重量那么为什么layout.height ??
  • 发布你的设置布局。
  • 请在答案中查看我的布局,因为我没有太多空间可以输入这个问题。
  • @kOsh 我已经提到了所有布局的重量......所以我不能在那里设置高度......
猜你喜欢
  • 2012-11-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-03-27
  • 1970-01-01
相关资源
最近更新 更多