ListView项目Onclick到新的片段活动 - "不幸的是,App已停止"

时间:2018-02-17 12:44:01

标签: android android-fragments virtual-reality

我为旅游景点制作VR View,在我的应用程序中,我有两个标签1)" Welcome Fragment"和2)" ttsd"。在ttsd片段中,我添加了listviewonclick。每当我选择ttsd调用的项目时,它总是崩溃("不幸的是,Atdrag App已经停止"但是然后我尝试更改并将其放到Activity它的工作原理。我在下面添加了我的代码。我认为我的代码在调用片段活动时出错了。

MainActivity 标签布局:

package com.example.computer.vratdragfinal;

import android.os.Bundle;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentStatePagerAdapter;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        TabLayout tabLayout = (TabLayout) findViewById(R.id.tab_layout);
        assert tabLayout != null;
        tabLayout.addTab(tabLayout.newTab().setText(R.string.welcome));
        tabLayout.addTab(tabLayout.newTab().setText(R.string.venue));
        tabLayout.setTabGravity(TabLayout.GRAVITY_FILL);
        final ViewPager viewPager = (ViewPager) findViewById(R.id.pager);
        final PagerAdapter adapter = new FragmentStatePagerAdapter(getSupportFragmentManager()) {

            @Override
            public Fragment getItem(int position) {
                switch (position) {
                    case 0:
                        return new WelcomeFragment();
                    case 1:
                        return new ttsd();
                }
                return null;
            }

            @Override
            public int getCount() {
                return 2;
            }
        };
        assert viewPager != null;
        viewPager.setAdapter(adapter);
        viewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout));
        tabLayout.setOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
            @Override
            public void onTabSelected(TabLayout.Tab tab) {
                viewPager.setCurrentItem(tab.getPosition());
            }

            @Override
            public void onTabUnselected(TabLayout.Tab tab) {

            }

            @Override
            public void onTabReselected(TabLayout.Tab tab) {

            }
        });
    }

    public void refreshNow() {
        finish();
        overridePendingTransition(0,0);
        startActivity(getIntent());
        overridePendingTransition(0,0);

    }

}

ttsd 片段活动:

package com.example.computer.vratdragfinal;

import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.widget.SwipeRefreshLayout;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;
import android.content.Intent;
import android.widget.AdapterView;

public class ttsd extends Fragment {

    public ttsd() {
        // Required empty public constructor
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.ttsd, container, false);
        // Inflate the layout for this fragment
        String[] awayStrings = {"Tubbataha Reef", "San Agustin Church", "Mayon Volcano", "Malapascua Island",
                "Puerto Galera", "Puerto Princesa Undergound River", "Donsol", "Banaue Rice Terraces",};

        ListView lv = (ListView) view.findViewById(R.id.listView2);

        ArrayAdapter<String> lva = new ArrayAdapter<String>(
                getActivity(), android.R.layout.simple_list_item_1, awayStrings);
        lv.setAdapter(lva);

        lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view,
                                    int position, long id) {
                if(position==0) {
                    Intent myintent = new Intent(view.getContext(), toptourist1.class);
                    startActivityForResult(myintent, 0);
                }

                if(position==1) {
                    Intent myintent = new Intent(view.getContext(), toptourist2.class);
                    startActivityForResult(myintent, 1);
                }
            }
        });

        final SwipeRefreshLayout mSwipeRefreshLayout = (SwipeRefreshLayout) view.findViewById(R.id.fragment_away);

        mSwipeRefreshLayout.setOnRefreshListener(
                new SwipeRefreshLayout.OnRefreshListener() {
                    @Override
                    public void onRefresh() {
                        ((MainActivity) getActivity()).refreshNow();
                        Toast.makeText(getContext(), "Refresh Layout working", Toast.LENGTH_LONG).show();

                    }
                }
        );

        return view;
    }

}

toptourist1 点击ttsd中的项目时片段活动崩溃:

package com.example.computer.vratdragfinal;

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.google.vr.sdk.widgets.pano.VrPanoramaView;

public class toptourist1 extends Fragment {

    private VrPanoramaView panoWidgetView;
    private ImageLoaderTask backgroundImageLoaderTask;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View v =  inflater.inflate(R.layout.activity_toptourist1, container,false);
        panoWidgetView = (VrPanoramaView) v.findViewById(R.id.pano_view);
        return v;
    }

    @Override
    public void onPause() {
        panoWidgetView.pauseRendering();
        super.onPause();
    }

    @Override
    public void onResume() {
        panoWidgetView.resumeRendering();
        super.onResume();
    }

    @Override
    public void onDestroy() {

        panoWidgetView.shutdown();
        super.onDestroy();
    }

    private synchronized void loadPanoImage() {
        ImageLoaderTask task = backgroundImageLoaderTask;
        if (task != null && !task.isCancelled()) {
            task.cancel(true);
        }

        VrPanoramaView.Options viewOptions = new VrPanoramaView.Options();
        viewOptions.inputType = VrPanoramaView.Options.TYPE_STEREO_OVER_UNDER;

        String panoImageName = "sample_converted.jpg";

        task = new ImageLoaderTask(panoWidgetView, viewOptions, panoImageName);
        task.execute(getActivity().getAssets());
        backgroundImageLoaderTask = task;
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        loadPanoImage();
    }

}

logcat的

E/AndroidRuntime: FATAL EXCEPTION: main
                  Process: com.example.computer.vratdragfinal, PID: 5850
                  java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.example.computer.vratdragfinal/com.example.computer.vratdragfinal.toptourist1}: java.lang.ClassCastException: com.example.computer.vratdragfinal.toptourist1 cannot be cast to android.app.Activity
                      at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2236)
                      at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2387)
                      at android.app.ActivityThread.access$800(ActivityThread.java:151)
                      at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1303)
                      at android.os.Handler.dispatchMessage(Handler.java:102)
                      at android.os.Looper.loop(Looper.java:135)
                      at android.app.ActivityThread.main(ActivityThread.java:5254)
                      at java.lang.reflect.Method.invoke(Native Method)
                      at java.lang.reflect.Method.invoke(Method.java:372)
                      at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903)
                      at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)
                   Caused by: java.lang.ClassCastException: com.example.computer.vratdragfinal.toptourist1 cannot be cast to android.app.Activity
                      at android.app.Instrumentation.newActivity(Instrumentation.java:1066)
                      at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2226)
                      at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2387) 
                      at android.app.ActivityThread.access$800(ActivityThread.java:151) 
                      at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1303) 
                      at android.os.Handler.dispatchMessage(Handler.java:102) 
                      at android.os.Looper.loop(Looper.java:135) 
                      at android.app.ActivityThread.main(ActivityThread.java:5254) 
                      at java.lang.reflect.Method.invoke(Native Method) 
                      at java.lang.reflect.Method.invoke(Method.java:372) 
                      at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903) 
                      at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698) 
Application terminated.

3 个答案:

答案 0 :(得分:1)

查看下面的Logcat行:

 Caused by: java.lang.ClassCastException: com.example.computer.vratdragfinal.toptourist1 cannot be cast to android.app.Activity

它告诉您,Android无法将toptourist1课程投放到Activity,因为Android期待Activity课程。

要开始Activity,您应该创建一个IntentActivity。您正在使用Fragment类创建一个intent。 startActivityForResult方法用于启动Activity非片段。

  Intent myintent = new Intent(view.getContext(), toptourist2.class);
  startActivityForResult(myintent, 1);

此处Intent构造函数的第二个参数应该是Activity类。如果您想使用Fragment,则必须使用FragmentTransaction

检查Fragment教程并查看this问题和答案。

答案 1 :(得分:0)

您需要先调用片段

    public void selectItem(MenuItem i){
            Fragment f = null;
            Class fClass;

答案 2 :(得分:0)

Toptourist1和toptourist2是片段,你打开它们就像有意图的活动一样。而不是

Intent intent = new Intent(view.getContext(), toptourist1.class);

你应该写

toptourist1 fragment = new toptourist1(); 
FragmentTransaction transaction = getFragmentManager().beginTransaction();
transaction.replace(R.id.fragment_container, fragment); // give your fragment container id in first parameter
transaction.addToBackStack(null);  // if written, this transaction will be added to backstack
transaction.commit();

startActivityForResult()用于从活动而不是片段中获取数据。我建议你查看有关片段的官方文档。