chengy8937
2021-07-21 17:01
采纳率: 100%
浏览 34

安卓开发:fragment里面listview开始监听后,为何底部导航失效?

安卓开发:fragment里面listview开始监听后,为何底部导航失效?
我做了底部导航,第二,第三之间可以切换
第一个用replace开了一个界面,里面有个listview 用了OnItemClickListener
结果是一旦第一个fragment加载,那么listview 可以监听
但是底部菜单全部失效,点哪里都是listview 响应 !
下面是MainActivity

package com.example.hello2;

import android.Manifest;
import android.app.Activity;
import android.content.ActivityNotFoundException;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.StrictMode;
import android.text.format.DateUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import com.example.hello2.activity.imageseg.StillCutPhotoActivity;

import com.example.hello2.ui.PictureLoader;
import com.google.android.material.bottomnavigation.BottomNavigationView;

import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentTransaction;
import androidx.navigation.NavController;
import androidx.navigation.Navigation;
import androidx.navigation.ui.AppBarConfiguration;
import androidx.navigation.ui.NavigationUI;

import com.example.hello2.databinding.ActivityMainBinding;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.security.Signature;
import java.util.ArrayList;

public class MainActivity extends AppCompatActivity  implements View.OnClickListener  {

    private RelativeLayout fra1;
    private RelativeLayout fra2;
    private RelativeLayout fra3;
    private RelativeLayout fra4;
    private FragmentTransaction transaction =null;
    private FragmentManager fm=null ;

    private afra1 afra1;
    private afra2 afra2;
    private afra3 afra3;

    private static final String TAG ="";
    private ActivityMainBinding binding;
    private Button showBtn;
    private ImageView showImg;
    private ArrayList<String> urls;
    private int curPos = 0;
    private PictureLoader loader;

    private TextView txt_title;
    private FrameLayout fl_content;
    private Context mContext;
    private ArrayList<afra1_Data> datas = null;
    //private android.app.FragmentManager fManager = null;
    private long exitTime = 0;


    public static String accessKey = ".........012"; //取值为获取的AK
    public static String securityKey = "..............012";  //取值为获取的SK


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // http 不执行问题
        StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder()
                //.detectDiskReads()
                //.detectDiskWrites()
                //.detectNetwork()   // or .detectAll() for all detectable problems
                .penaltyLog()
                .build());
        StrictMode.setVmPolicy(new StrictMode.VmPolicy.Builder()
                .detectLeakedSqlLiteObjects()
                .detectLeakedClosableObjects()
                .penaltyLog()
                .penaltyDeath()
                .build());
        // http 不执行问题   END

        binding = ActivityMainBinding.inflate(getLayoutInflater());
        setContentView(binding.getRoot());

//        BottomNavigationView navView = findViewById(R.id.nav_view);




        // Passing each menu ID as a set of Ids because each
        // menu should be considered as top level destinations.
        AppBarConfiguration appBarConfiguration = new AppBarConfiguration.Builder(
                R.id.navigation_home, R.id.navigation_dashboard, R.id.navigation_notifications)
                .build();
        //NavController navController = Navigation.findNavController(this, R.id.nav_host_fragment_activity_main);
        //NavigationUI.setupActionBarWithNavController(this, navController, appBarConfiguration);
        //NavigationUI.setupWithNavController(binding.navView, navController);

        //申请权限
        if (Build.VERSION.SDK_INT >= 23) {
            int REQUEST_CODE_CONTACT = 101;
            String[] permissions = {Manifest.permission.READ_EXTERNAL_STORAGE};
            //验证是否许可权限
            for (String str : permissions) {
                if (this.checkSelfPermission(str) != PackageManager.PERMISSION_GRANTED) {
                    //申请权限
                    this.requestPermissions(permissions, REQUEST_CODE_CONTACT);
                }
            }
        }

        setContentView(R.layout.activity_main);
        loader = new PictureLoader();
        initData();
        initUI();
        initView();
        //try {
        //    ObsPut.main(new String[]{"", ""});
        //}
        //catch (Exception e)
        //{

        //}
    }

    private void initData() {
        urls = new ArrayList<>();
        urls.add("http://ww4.sinaimg.cn/large/610dc034jw1f6ipaai7wgj20dw0kugp4.jpg");
        urls.add("http://ww3.sinaimg.cn/large/610dc034jw1f6gcxc1t7vj20hs0hsgo1.jpg");
        urls.add("http://ww4.sinaimg.cn/large/610dc034jw1f6f5ktcyk0j20u011hacg.jpg");
        urls.add("http://ww1.sinaimg.cn/large/610dc034jw1f6e1f1qmg3j20u00u0djp.jpg");
        urls.add("http://ww3.sinaimg.cn/large/610dc034jw1f6aipo68yvj20qo0qoaee.jpg");
        urls.add("http://ww3.sinaimg.cn/large/610dc034jw1f69c9e22xjj20u011hjuu.jpg");
        urls.add("http://ww3.sinaimg.cn/large/610dc034jw1f689lmaf7qj20u00u00v7.jpg");
        urls.add("http://ww3.sinaimg.cn/large/c85e4a5cjw1f671i8gt1rj20vy0vydsz.jpg");
        urls.add("http://ww2.sinaimg.cn/large/610dc034jw1f65f0oqodoj20qo0hntc9.jpg");
        urls.add("http://ww2.sinaimg.cn/large/c85e4a5cgw1f62hzfvzwwj20hs0qogpo.jpg");
    }

    private void initView() {
        this.fra1 = this.findViewById(R.id.fra1);    //选本人照按钮
        this.fra2 = this.findViewById(R.id.fra2);      //剪切按钮
        this.fra3 = this.findViewById(R.id.fra3);     //换背景
        this.fra4 = this.findViewById(R.id.fra4);  //存盘
        fm = getSupportFragmentManager();
        //fm = getFragmentManager();
        setDefaultFragment();
        fra1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Log.i(TAG, "点击第1选项");
                //super.onCreate(savedInstanceState);
                setContentView(R.layout.activity_main);
                mContext = MainActivity.this;
                //fManager = getFragmentManager();

                datas = new ArrayList<afra1_Data>();
                for (int i = 1; i <= 10; i++) {
                    afra1_Data data = new afra1_Data(urls.get(i - 1), i + "~新闻内容~~~~~~~~");
                    datas.add(data);
                }
                //android.app.FragmentTransaction ft = fManager.beginTransaction();
                //afra1  = new afra1(fManager, datas);
                //ft.replace(R.id.fl_content, afra1);
                //ft.commit();
                Log.i(TAG, "点击第1选项");
                transaction = fm.beginTransaction();
                afra1=new afra1(fm,datas);
                transaction.replace(R.id.fl_content,afra1);
                //transaction.add(R.id.fl_content,afra1);
                bindViews();
                transaction.commit();
            }
        });

        fra2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Log.i(TAG, "点击第二选项");
                transaction = fm.beginTransaction();
                afra2=new afra2();
                transaction.replace(R.id.fl_content,afra2);
                bindViews();
                transaction.commit();
            }
        });
        fra3.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Log.i(TAG, "点击第3选项");
                transaction = fm.beginTransaction();
                afra3=new afra3();
                transaction.replace(R.id.fl_content,afra3);
                bindViews();
                transaction.commit();
            }
        });
    }

    private void bindViews() {
       txt_title = (TextView) findViewById(R.id.txt_title);
       fl_content = (FrameLayout) findViewById(R.id.fl_content);
    }


    private void setDefaultFragment()
    {
        transaction = fm.beginTransaction();
        afra2=new afra2();
        transaction.replace(R.id.fl_content,afra2);
        bindViews();
        transaction.commit();
    }

    private void initUI() {
        showBtn = (Button) findViewById(R.id.btn_show);
    //    showImg = (ImageView) findViewById(R.id.img_show);
        showBtn.setOnClickListener(this);
        //SignDemo=new SignDemo();
            }

    private void openSystemFile() {
        Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
        intent.setType("*/*");
        intent.putExtra(Intent.EXTRA_ALLOW_MULTIPLE, true);//打开多个文件
        intent.addCategory(Intent.CATEGORY_DEFAULT);
        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
        try {
            startActivityForResult(Intent.createChooser(intent, "请选择文件"), 1);
        } catch (ActivityNotFoundException e) {
            e.printStackTrace();
            Toast.makeText(this, "请 安装文件管理器", Toast.LENGTH_SHORT);
        }
    }
    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 1 && resultCode == Activity.RESULT_OK) {
            //Get the Uri of the selected file


            if(data.getClipData() != null) {//有选择多个文件
                int count = data.getClipData().getItemCount();
                Log.i(TAG,"url count :  "+ count);
                int currentItem = 0;

                while(currentItem < count) {
                    Uri imageUri = data.getClipData().getItemAt(currentItem).getUri();
                    String imgpath = ContentUriUtil.getPath(this,imageUri);
                    Log.i(TAG,"url "+ imgpath);

                    //do something with the image (save it to some directory or whatever you need to do with it here)
                    currentItem = currentItem + 1;
                }

            } else if(data.getData() != null) {//只有一个文件咯
                String imagePath = ContentUriUtil.getPath(this,data.getData());
                Log.i(TAG,"Single image path ---- "+ imagePath);


                //do something with the image (save it to some directory or whatever you need to do with it here)
            }

        }
    }

    public void onClick(View v) {
       // openSystemFile();


        //拍照界面
        Intent intent = new Intent(this, Activity_add.class);
        startActivity(intent);

        //抠图界面
//        Intent intent = new Intent(this, StillCutPhotoActivity.class);
//        startActivity(intent);


      //  switch (v.getId()) {
      //      case R.id.btn_show:
      //          if (curPos > 9) {
      //              curPos = 0;
      //          }
      //          loader.load(showImg, urls.get(curPos));
      //          curPos++;
      //          break;
       // }
    }


}

第一个fragment:
```java

package com.example.hello2;

import android.annotation.SuppressLint;
import androidx.fragment.app.Fragment;
//import android.app.FragmentManager;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentTransaction;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;

import android.widget.AdapterView.OnItemClickListener;

import android.widget.ListView;
import android.widget.TextView;

import org.xutils.view.annotation.Event;

import java.util.ArrayList;

/**
 * Created by Jay on 2015/9/6 0006.
 */

public class afra1 extends Fragment  {
    private FragmentManager fManager;
    private ArrayList<afra1_Data> datas;
    private ListView list_news;

    public afra1(FragmentManager fManager, ArrayList<afra1_Data> datas) {
        this.fManager = fManager;
        this.datas = datas;
    }

    @Override
    @Event(value=R.id.list_news,type= OnItemClickListener.class)
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.afra1, container, false);
        list_news = (ListView) view.findViewById(R.id.list_news);
        afra1_MyAdapter myAdapter = new afra1_MyAdapter(datas, getActivity());
        list_news.setAdapter(myAdapter);
        //list_news.setOnItemClickListener(this);

        list_news.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                Log.i("点击事件", String.valueOf(position)+"  [id]"+String.valueOf(id));
            }

        });





        return view;
    }


}

activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@color/primary_background"
    android:fitsSystemWindows="true"
    android:keepScreenOn="true"
    android:orientation="vertical">
    <Button
        android:id="@+id/btn_show"
        android:layout_width="match_parent"
        android:layout_height="64dp"
        android:text="按钮"
        android:clickable="true"
        />
    <TextView
        android:id="@+id/txt_title"
        android:layout_width="match_parent"
        android:layout_height="56dp"
        android:background="@color/black"
        android:textColor="@color/white"
        android:text="新闻列表"
        android:textSize="20sp"
        android:textStyle="bold"
        android:gravity="center"/>

    <FrameLayout
        android:id="@+id/fl_content"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_below="@id/txt_title">
    </FrameLayout>

    <LinearLayout
        android:id="@+id/linear_views"
        android:layout_width="match_parent"
        android:layout_height="90dp"
        android:paddingBottom="10dp"
        android:layout_alignParentBottom="true"
        android:background="@color/white"
        android:orientation="horizontal">

        <RelativeLayout
            android:id="@+id/fra1"
            android:layout_width="0dp"
            android:layout_height="match_parent"
            android:layout_weight="1"
            android:clickable="false">

            <RelativeLayout
                android:layout_width="30dp"
                android:layout_height="30dp"
                android:layout_centerHorizontal="true"
                android:layout_marginTop="20dp"
                android:orientation="vertical">

                <ImageView
                    android:layout_width="25dp"
                    android:layout_height="25dp"
                    android:layout_centerHorizontal="true"
                    android:src="@mipmap/album_black"></ImageView>

            </RelativeLayout>

            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_alignParentBottom="true"
                android:layout_centerHorizontal="true"
                android:layout_marginBottom="10dp"
                android:gravity="center"
                android:text="@string/select_picture"
                android:textColor="@color/secondary_text_color"
                android:textSize="@dimen/text_size_11sp"></TextView>
        </RelativeLayout>

        <View
            android:layout_width="0.1dp"
            android:layout_height="match_parent"
            android:layout_marginTop="10dp"
            android:layout_marginBottom="10dp"
            android:background="@color/primary_text_color"></View>

        <RelativeLayout
            android:id="@+id/fra2"
            android:layout_width="0dp"
            android:layout_height="match_parent"
            android:layout_weight="1"
            android:clickable="false">

            <RelativeLayout
                android:layout_width="30dp"
                android:layout_height="30dp"
                android:layout_centerHorizontal="true"
                android:layout_marginTop="20dp"
                android:background="@android:color/white"
                android:orientation="vertical">

                <ImageView
                    android:layout_width="25dp"
                    android:layout_height="25dp"
                    android:layout_centerHorizontal="true"
                    android:src="@drawable/icon_cut"></ImageView>

            </RelativeLayout>

            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_alignParentBottom="true"
                android:layout_centerHorizontal="true"
                android:layout_marginBottom="10dp"
                android:gravity="center"
                android:text="@string/cut"
                android:textColor="@color/secondary_text_color"
                android:textSize="@dimen/text_size_11sp"></TextView>

        </RelativeLayout>

        <View
            android:layout_width="0.1dp"
            android:layout_height="match_parent"
            android:layout_marginTop="10dp"
            android:layout_marginBottom="10dp"
            android:background="@color/primary_text_color"></View>

        <RelativeLayout
            android:id="@+id/fra3"
            android:layout_width="0dp"
            android:layout_height="match_parent"
            android:layout_weight="1"
            android:clickable="false">

            <RelativeLayout
                android:layout_width="30dp"
                android:layout_height="30dp"
                android:layout_marginTop="22dp"
                android:layout_centerHorizontal="true"
                android:background="@android:color/white"
                android:orientation="vertical">

                <ImageView
                    android:layout_width="25dp"
                    android:layout_height="25dp"
                    android:layout_centerHorizontal="true"
                    android:src="@drawable/icons_background"></ImageView>

            </RelativeLayout>

            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_centerHorizontal="true"
                android:layout_alignParentBottom="true"
                android:layout_marginBottom="10dp"
                android:gravity="center"
                android:text="@string/replace_background"
                android:textColor="@color/secondary_text_color"
                android:textSize="@dimen/text_size_11sp"></TextView>
        </RelativeLayout>

        <View
            android:layout_width="0.1dp"
            android:layout_height="match_parent"
            android:layout_marginTop="10dp"
            android:layout_marginBottom="10dp"
            android:background="@color/primary_text_color"></View>

        <RelativeLayout
            android:id="@+id/fra4"
            android:layout_width="0dp"
            android:layout_height="match_parent"
            android:layout_weight="1"
            android:gravity="center">

            <RelativeLayout
                android:layout_width="30dp"
                android:layout_height="30dp"
                android:layout_marginTop="22dp"
                android:layout_centerHorizontal="true"
                android:background="@android:color/white"
                android:orientation="vertical">

                <ImageView
                    android:layout_width="25dp"
                    android:layout_height="25dp"
                    android:layout_centerHorizontal="true"
                    android:src="@drawable/icons_save"></ImageView>

            </RelativeLayout>

            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_centerHorizontal="true"
                android:layout_alignParentBottom="true"
                android:layout_marginBottom="10dp"
                android:gravity="center"
                android:text="@string/save"
                android:textColor="@color/secondary_text_color"
                android:textSize="@dimen/text_size_11sp"></TextView>
        </RelativeLayout>
    </LinearLayout>

</RelativeLayout>

afra1.xml

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/afra1"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="afra1">

    <ListView
        android:id="@+id/list_news"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        />
</androidx.constraintlayout.widget.ConstraintLayout>



afra1_list_item.xml
<?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">

    <ImageView
        android:id="@+id/pitem"
        android:layout_width="380dp"
        android:layout_height="213dp"
/>

</LinearLayout>

afra1_MyAdpter.java


```java
package com.example.hello2 ;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;

import com.huawei.hms.framework.common.Utils;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.*;

/**
 * Created by Jay on 2015/9/6 0006.
 */
public class afra1_MyAdapter extends BaseAdapter{

    private List<afra1_Data> mData;
    private Context mContext;
    FileCache fileCache;
    public afra1_MyAdapter(List<afra1_Data> mData, Context mContext) {
        this.mData = mData;
        this.mContext = mContext;
    }

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

    @Override
    public Object getItem(int position) {
        return null;
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        ViewHolder viewHolder;
        if(convertView == null){
            convertView = LayoutInflater.from(mContext).inflate(R.layout.afra1_list_item,parent,false);
            viewHolder = new ViewHolder();
            viewHolder.pic_item_title = (ImageView) convertView.findViewById(R.id.pitem);
            convertView.setTag(viewHolder);
        }else{
            viewHolder = (ViewHolder) convertView.getTag();
        }
        ImageLoader img=new ImageLoader();
        viewHolder.pic_item_title.setImageBitmap(img.getBitmapFromURL(mData.get(position).getNew_title()));
        Log.i("信息:getView"+String.valueOf(position), mData.get(position).getNew_title());
        return convertView;
    }

    private class ViewHolder{
        ImageView pic_item_title;
    }

}



  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

5条回答 默认 最新

  • chengy8937 2021-07-22 10:22
    已采纳

    我的AFFF3是用ListFragment 做的,没毛病
    AFFF1是用Fragment+ListView 做的,有毛病
    我把AFFF1替换AFFF3的代码,居然也有毛病了。
    这才发现,原来罪魁祸首出在MainActivity.java

    里面从网上例子里面拷贝过来的有两句话:在做transaction replace之前,
    setContentView(R.layout.activity_main);
    mContext = MainActivity.this;
    应该就是第一句惹的祸,原理还不清楚,删掉就全都正常了。
    再次感谢夕阳的帮助!

    点赞 打赏 评论
  • 夕阳映明月 2021-07-21 18:27

    这个应该是涉及到事件传播机制的问题,你可以在activity_main中的FrameLayout修改成


    使FrameLayout位于标题栏和导航之间。不会出现重叠就没问题了。你那样做使底部导航栏叠在了FrameLayout上面,虽然是叠在FrameLayout上,点击的时候会同时点到该item和底部导航栏,然而FrameLayout中ListView的Item先把点击事件给消费了,导致导航栏的点击没生效

    点赞 1 打赏 评论
  • 夕阳映明月 2021-07-21 18:29


    点赞 1 打赏 评论
  • 夕阳映明月 2021-07-21 18:31

    咦!写的代码怎么显示不出来,算了你在activity_main的FrameLayout加上android:layout_above="@id/linear_views",使FrameLayout位于头部按钮和底部导航栏之间即可

    点赞 1 打赏 评论
  • chengy8937 2021-07-22 00:27

    唉,改来改去也是不对
    最后网上找了一个 ListFragment 例子,套了一下终于能用了,算了不折腾了。
    多谢夕阳的帮忙,多谢

    点赞 打赏 评论

相关推荐 更多相似问题