Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/android/195.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Android 如何分别在70幅图像的不同点上分配按钮?_Android_Android Fragments - Fatal编程技术网

Android 如何分别在70幅图像的不同点上分配按钮?

Android 如何分别在70幅图像的不同点上分配按钮?,android,android-fragments,Android,Android Fragments,我的问题: 我有70张图片,我想在每张图片上加上透明按钮 这样,当用户点击它时,它会播放一段短音频 关于图像上的斑点。图像显示在查看页面中 我的解决方案: 现在我想到的是,我可以创建70个片段,每个片段包含各自的图像作为背景,我可以轻松地在每个点上指定按钮,并为这些按钮指定操作,这些按钮将播放各自的音频 但是 class PagerHolder extends Fragment { //buttons list - here, arrayList index represents page n

我的问题:

我有70张图片,我想在每张图片上加上透明按钮 这样,当用户点击它时,它会播放一段短音频 关于图像上的斑点。图像显示在
查看页面

我的解决方案:

现在我想到的是,我可以创建70个片段,每个片段包含各自的图像作为背景,我可以轻松地在每个点上指定按钮,并为这些按钮指定操作,这些按钮将播放各自的音频

但是

class PagerHolder extends Fragment {

//buttons list - here, arrayList index represents page number
//and at each index we have map of buttons (buttons in each of these pages) and the related audio files
private ArrayList<Map<Button, RelatedAudioFile>> pageButtonsList = new ArrayList<>();
//pager view
private ViewPager viewPager;
//pager adapter
private PagerAdapter pagerAdapter;
//current page number -- page in which we are in right now
private int currentpageNumber = 0;

//buttonListener -- one button listener for all the buttons in all the pages.
private View.OnClickListener listener = new View.OnClickListener() {
    @Override
    public void onClick(View buttonView) {
         //here you can play the audio.
         //buttonView -- is the same button-object that was pressed.
        ((RelatedAudioFile)pageButtonsList.get(currentpageNumber).get(buttonView)).play();

    }
};

 @Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    pagerAdapter = new PagerAdapter(getChildFragmentManager());

    //add buttons to the list
    //page 0 buttons
    HashMap<Button, RelatedAudioFile> page0Buttons = new HashMap<>();
    page0Buttons.put(new Button(context), new RelatedAudioFile());
    page0Buttons.put(new Button(context), new RelatedAudioFile());
    page0Buttons.put(new Button(context), new RelatedAudioFile());
    pageButtonsList.add(page0Buttons)

    //Adding page 1 buttons:
    HashMap<Button, RelatedAudioFile> page1Buttons = new HashMap<>();
    page1Buttons.put(new Button(context), new RelatedAudioFile());
    pageButtonsList.add(page1Buttons);

    //Adding page 2 buttons:
    HashMap<Button, RelatedAudioFile> page2Buttons = new HashMap<>();
    page2Buttons.put(new Button(context), new RelatedAudioFile());
    page2Buttons.put(new Button(context), new RelatedAudioFile());
    pageButtonsList.add(page2Buttons);

    for(Map<Button, RelatedAudioFile> pageButtons :pageButtonsList) {
       for(Button button : pageButtons.keySet()) {
           button.setOnClickListener(listener);
        }
    }

}



 @Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
    View v = inflater.inflate(R.layout.fragment_editor_pager, container, false);

    viewPager = (ViewPager) v.findViewById(R.id.view_pager);
    viewPager.setAdapter(pagerAdapter);

    return v;
}



 private class PagerAdapter extends FragmentPagerAdapter {

    private ButtonFragment buttonFragment;

    private PagerAdapter(FragmentManager fm) {
        super(fm);
    }

    @Override
    public Fragment getItem(int pageNumber) {
        currentpageNumber = pageNumber;

       //pass the buttons to the fragment so that it can add these buttons to the screen 
        buttonFragment = ButtonFragment.newInstance(pageButtonsList.get(pageNumber).keySet());

        //to add buttons on screen programatically at certain position you can refer here:
        // http://stackoverflow.com/questions/3441475/android-change-absolute-position-of-a-view-programmatically
    }

    //number of pages
    @Override
    public int getCount() {
        return 70;
    }
}
在一个应用程序中包含70个片段似乎不是一个好方法


那么我如何才能做到这一点,我可以使用什么更好的方法呢?

您不必创建70个片段。相反,您可以只使用一个ImageView,如下所示:

final List<Integer> list = new ArrayList<>();
list.add(R.drawable.img_0);
list.add(R.drawable.img_1);
...
list.add(R.drawable.img_69);

ImageView img = (ImageView)findViewById(R.id.imageView);
img.setBackgroundResource(list.get(yourIndex));
img.setOnClickListener(new OnClickListener());//plays the audio
final List=new ArrayList();
添加列表(R.drawable.img_0);
列表。添加(R.drawable.img_1);
...
列表。添加(R.drawable.img_69);
ImageView img=(ImageView)findViewById(R.id.ImageView);
setBackgroundResource(list.get(yourIndex));
setOnClickListener(新的OnClickListener())//播放音频

您不需要声明70个片段,只需创建一个片段,然后在该片段上声明图像和声音的全局数组。现在,当您在片段处重定向时,只需在参数中传递一个整数变量。现在,您可以使用该整数变量显示来自阵列的图像,单击按钮,您可以使用相同的整数播放来自声音阵列的音频

我们只需要一个片段,就可以创建一个Map(Button,RelatedAudioFile)数据结构的ArrayList,用于保存按钮和相关音频文件。ArrayList索引表示页码

例如: 现在假设我们有3个视图页。由于大多数PagerAdapter索引都是从“0”开始的,所以假设第0页包含3个按钮,第1页包含1个按钮,第2页包含2个按钮

伪代码:

class PagerHolder extends Fragment {

//buttons list - here, arrayList index represents page number
//and at each index we have map of buttons (buttons in each of these pages) and the related audio files
private ArrayList<Map<Button, RelatedAudioFile>> pageButtonsList = new ArrayList<>();
//pager view
private ViewPager viewPager;
//pager adapter
private PagerAdapter pagerAdapter;
//current page number -- page in which we are in right now
private int currentpageNumber = 0;

//buttonListener -- one button listener for all the buttons in all the pages.
private View.OnClickListener listener = new View.OnClickListener() {
    @Override
    public void onClick(View buttonView) {
         //here you can play the audio.
         //buttonView -- is the same button-object that was pressed.
        ((RelatedAudioFile)pageButtonsList.get(currentpageNumber).get(buttonView)).play();

    }
};

 @Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    pagerAdapter = new PagerAdapter(getChildFragmentManager());

    //add buttons to the list
    //page 0 buttons
    HashMap<Button, RelatedAudioFile> page0Buttons = new HashMap<>();
    page0Buttons.put(new Button(context), new RelatedAudioFile());
    page0Buttons.put(new Button(context), new RelatedAudioFile());
    page0Buttons.put(new Button(context), new RelatedAudioFile());
    pageButtonsList.add(page0Buttons)

    //Adding page 1 buttons:
    HashMap<Button, RelatedAudioFile> page1Buttons = new HashMap<>();
    page1Buttons.put(new Button(context), new RelatedAudioFile());
    pageButtonsList.add(page1Buttons);

    //Adding page 2 buttons:
    HashMap<Button, RelatedAudioFile> page2Buttons = new HashMap<>();
    page2Buttons.put(new Button(context), new RelatedAudioFile());
    page2Buttons.put(new Button(context), new RelatedAudioFile());
    pageButtonsList.add(page2Buttons);

    for(Map<Button, RelatedAudioFile> pageButtons :pageButtonsList) {
       for(Button button : pageButtons.keySet()) {
           button.setOnClickListener(listener);
        }
    }

}



 @Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
    View v = inflater.inflate(R.layout.fragment_editor_pager, container, false);

    viewPager = (ViewPager) v.findViewById(R.id.view_pager);
    viewPager.setAdapter(pagerAdapter);

    return v;
}



 private class PagerAdapter extends FragmentPagerAdapter {

    private ButtonFragment buttonFragment;

    private PagerAdapter(FragmentManager fm) {
        super(fm);
    }

    @Override
    public Fragment getItem(int pageNumber) {
        currentpageNumber = pageNumber;

       //pass the buttons to the fragment so that it can add these buttons to the screen 
        buttonFragment = ButtonFragment.newInstance(pageButtonsList.get(pageNumber).keySet());

        //to add buttons on screen programatically at certain position you can refer here:
        // http://stackoverflow.com/questions/3441475/android-change-absolute-position-of-a-view-programmatically
    }

    //number of pages
    @Override
    public int getCount() {
        return 70;
    }
}
类PagerHolder扩展片段{
//按钮列表-此处,arrayList索引表示页码
//在每个索引中,我们都有按钮地图(这些页面中的每个按钮)和相关的音频文件
private ArrayList pageButtonsList=新建ArrayList();
//寻呼机视图
私人视页机视页机;
//寻呼机适配器
私人寻呼机;
//当前页码--我们现在所在的页面
private int currentpageNumber=0;
//buttonListener——所有页面中所有按钮的一个按钮侦听器。
private View.OnClickListener=new View.OnClickListener(){
@凌驾
单击“公共无效”(查看按钮查看){
//在这里你可以播放音频。
//buttonView——与按下的按钮对象相同。
((RelatedAudioFile)pageButtonsList.get(currentpageNumber.get(buttonView)).play();
}
};
@凌驾
创建时的公共void(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
pagerAdapter=新的pagerAdapter(getChildFragmentManager());
//将按钮添加到列表中
//第0页按钮
HashMap page0Buttons=新建HashMap();
page0Buttons.put(新建按钮(上下文),新建RelatedAudioFile());
page0Buttons.put(新建按钮(上下文),新建RelatedAudioFile());
page0Buttons.put(新建按钮(上下文),新建RelatedAudioFile());
PageButtons列表。添加(Page0按钮)
//添加第1页按钮:
HashMap page1Buttons=新建HashMap();
page1Buttons.put(新建按钮(上下文),新建RelatedAudioFile());
PageButtons列表。添加(page1Buttons);
//添加第2页按钮:
HashMap page2Buttons=新建HashMap();
page2Buttons.put(新建按钮(上下文),新建RelatedAudioFile());
page2Buttons.put(新建按钮(上下文),新建RelatedAudioFile());
PageButtons列表。添加(page2Buttons);
用于(地图页面按钮:页面按钮列表){
用于(按钮:pageButtons.keySet()){
setOnClickListener(listener);
}
}
}
@凌驾
创建视图时的公共视图(LayoutFlater充气机、@Nullable ViewGroup容器、@Nullable Bundle savedInstanceState){
视图v=充气机。充气(R.layout.fragment\u editor\u pager,container,false);
viewPager=(viewPager)v.findViewById(R.id.view\u pager);
viewPager.setAdapter(pagerAdapter);
返回v;
}
私有类PagerAdapter扩展了FragmentPagerAdapter{
私人钮扣碎片钮扣碎片;
专用页雷达(碎片管理器fm){
超级(fm);
}
@凌驾
公共片段getItem(int页码){
currentpageNumber=页码;
//将按钮传递给片段,以便它可以将这些按钮添加到屏幕上
buttonFragment=buttonFragment.newInstance(PageButtonList.get(pageNumber.keySet());
//要以编程方式在屏幕上的特定位置添加按钮,您可以参考以下内容:
// http://stackoverflow.com/questions/3441475/android-change-absolute-position-of-a-view-programmatically
}
//页数
@凌驾
public int getCount(){
返回70;
}
}

使用此自定义视图寻呼机

import android.content.Context;
import android.support.v4.view.ViewPager;
import android.util.AttributeSet;
import android.view.MotionEvent;

/**
 * Created by Jinesh on 06-01-2016.
 */
public class CustomViewPager extends ViewPager {
    private boolean enabled;
    public CustomViewPager(Context context, AttributeSet attrs) {
        super(context, attrs);
        this.enabled = true;
    }
    @Override
    public boolean onTouchEvent(MotionEvent event) {
        if (this.enabled) {
            return super.onTouchEvent(event);
        }

        return false;
    }

    @Override
    public boolean onInterceptTouchEvent(MotionEvent event) {
/*
        if (this.enabled) {
            return super.onInterceptTouchEvent(event);
        }
*/

        return false;
    }

    public void setPagingEnabled(boolean enabled) {
        this.enabled = enabled;
    }
}
将此标记添加到xml中

<Your_package_name.CustomViewPager xmlns:android="http://schemas.android.com/apk/res/android"
            android:id="@+id/vP_asq_Pager"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_weight="1" />

我会这样做。请注意,这是一个单一类解决方案。例如,您可以将类分开

class PagerHolder extends Fragment {

//buttons list - here, arrayList index represents page number
//and at each index we have map of buttons (buttons in each of these pages) and the related audio files
private ArrayList<Map<Button, RelatedAudioFile>> pageButtonsList = new ArrayList<>();
//pager view
private ViewPager viewPager;
//pager adapter
private PagerAdapter pagerAdapter;
//current page number -- page in which we are in right now
private int currentpageNumber = 0;

//buttonListener -- one button listener for all the buttons in all the pages.
private View.OnClickListener listener = new View.OnClickListener() {
    @Override
    public void onClick(View buttonView) {
         //here you can play the audio.
         //buttonView -- is the same button-object that was pressed.
        ((RelatedAudioFile)pageButtonsList.get(currentpageNumber).get(buttonView)).play();

    }
};

 @Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    pagerAdapter = new PagerAdapter(getChildFragmentManager());

    //add buttons to the list
    //page 0 buttons
    HashMap<Button, RelatedAudioFile> page0Buttons = new HashMap<>();
    page0Buttons.put(new Button(context), new RelatedAudioFile());
    page0Buttons.put(new Button(context), new RelatedAudioFile());
    page0Buttons.put(new Button(context), new RelatedAudioFile());
    pageButtonsList.add(page0Buttons)

    //Adding page 1 buttons:
    HashMap<Button, RelatedAudioFile> page1Buttons = new HashMap<>();
    page1Buttons.put(new Button(context), new RelatedAudioFile());
    pageButtonsList.add(page1Buttons);

    //Adding page 2 buttons:
    HashMap<Button, RelatedAudioFile> page2Buttons = new HashMap<>();
    page2Buttons.put(new Button(context), new RelatedAudioFile());
    page2Buttons.put(new Button(context), new RelatedAudioFile());
    pageButtonsList.add(page2Buttons);

    for(Map<Button, RelatedAudioFile> pageButtons :pageButtonsList) {
       for(Button button : pageButtons.keySet()) {
           button.setOnClickListener(listener);
        }
    }

}



 @Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
    View v = inflater.inflate(R.layout.fragment_editor_pager, container, false);

    viewPager = (ViewPager) v.findViewById(R.id.view_pager);
    viewPager.setAdapter(pagerAdapter);

    return v;
}



 private class PagerAdapter extends FragmentPagerAdapter {

    private ButtonFragment buttonFragment;

    private PagerAdapter(FragmentManager fm) {
        super(fm);
    }

    @Override
    public Fragment getItem(int pageNumber) {
        currentpageNumber = pageNumber;

       //pass the buttons to the fragment so that it can add these buttons to the screen 
        buttonFragment = ButtonFragment.newInstance(pageButtonsList.get(pageNumber).keySet());

        //to add buttons on screen programatically at certain position you can refer here:
        // http://stackoverflow.com/questions/3441475/android-change-absolute-position-of-a-view-programmatically
    }

    //number of pages
    @Override
    public int getCount() {
        return 70;
    }
}
  • 这将一次只保留5个片段
  • 屏幕分为4个按钮,您可以根据需要设置按钮的alpha值和大小。例如,目前我将其保持为半透明
  • 我正在使用
    Glide
    加载图像,以避免由于图像加载而出现OOM问题
它看起来像什么

解决方案:-

package com.example.sample;

import java.util.ArrayList;

import com.bumptech.glide.Glide;

import android.content.Context;
import android.media.Ringtone;
import android.media.RingtoneManager;
import android.net.Uri;
import android.os.Bundle;
import android.os.Parcelable;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.widget.FrameLayout;
import android.widget.ImageView;

public class MainActivity extends FragmentActivity {

    private static ArrayList<Integer> imageList = new ArrayList<Integer>();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        // Load image data
        for (int i = 0; i < 70; i++) {
            imageList.add(R.drawable.ic_launcher);
        }

        if (savedInstanceState == null) {
            getSupportFragmentManager().beginTransaction()
                    .add(R.id.container, new PlaceholderFragment()).commit();
        }
    }

    /**
     * A placeholder fragment containing a simple view.
     */
    public static class PlaceholderFragment extends Fragment {

        public PlaceholderFragment() {
        }

        @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container,
                Bundle savedInstanceState) {
            View rootView = inflater.inflate(R.layout.fragment_main, container,
                    false);

            ViewPager viewPager = (ViewPager) rootView
                    .findViewById(R.id.image_pager);

            // Limit number of pages that should be retained to either
            // side of the current page
            viewPager.setOffscreenPageLimit(2);

            viewPager.setAdapter(new SongDetailAdapter(getActivity()));

            return rootView;
        }
    }

    public static class SongDetailAdapter extends PagerAdapter {

        Context mContext;
        LayoutInflater mLayoutInflater;

        public SongDetailAdapter(Context context) {
            mContext = context;
            mLayoutInflater = (LayoutInflater) mContext
                    .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        }

        @Override
        public int getCount() {

            return imageList.size();
        }

        @Override
        public boolean isViewFromObject(View view, Object object) {
            return view == ((FrameLayout) object);
        }

        @Override
        public Object instantiateItem(ViewGroup container, final int position) {
            View itemView = mLayoutInflater.inflate(
                    R.layout.image_place_holder, container, false);

            ImageView imageView = (ImageView) itemView
                    .findViewById(R.id.background);

            itemView.findViewById(R.id.button1).setOnClickListener(
                    new OnClickListener() {

                        @Override
                        public void onClick(View v) {
                            playSound(1);

                        }
                    });

            itemView.findViewById(R.id.button2).setOnClickListener(
                    new OnClickListener() {

                        @Override
                        public void onClick(View v) {

                            playSound(2);

                        }
                    });

            itemView.findViewById(R.id.button3).setOnClickListener(
                    new OnClickListener() {

                        @Override
                        public void onClick(View v) {
                            playSound(3);

                        }
                    });

            itemView.findViewById(R.id.button4).setOnClickListener(
                    new OnClickListener() {

                        @Override
                        public void onClick(View v) {
                            playSound(4);

                        }
                    });

            Glide.with(mContext).load("").placeholder(imageList.get(position))
                    .crossFade(300).into(imageView);

            container.addView(itemView);

            return itemView;
        }

        @Override
        public void destroyItem(ViewGroup container, int position, Object object) {
            container.removeView((FrameLayout) object);
        }

        @Override
        public Object instantiateItem(View arg0, int arg1) {
            // TODO Auto-generated method stub
            return null;
        }

        @Override
        public Parcelable saveState() {
            // TODO Auto-generated method stub
            return null;
        }

        /*
         * Play sound
         */
        private void playSound(int buttonNumber) {

            switch (buttonNumber) {
            case 1: // play sound for Button1
            case 2: // play sound for Button2
            case 3: // play sound for Button3
            case 4: // play sound for Button4
            default: // play sound for Button n

                // Playing default notification here for example
                Uri notification = RingtoneManager
                        .getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
                Ringtone r = RingtoneManager
                        .getRingtone(mContext, notification);
                r.play();
                break;
            }

        }

    }
}
package com.example.sample;
导入java.util.ArrayList;
导入com.bumptech.glide.glide;
导入android.content.Context;
导入android.media.Ringtone;
导入android.media.ringtonemager;
导入android.net.Uri;
导入android.os.Bundle;
导入android.os.Parcelable;
导入android.support.v4.app.Fragment;
导入android.support.v4.app.FragmentAc
<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"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="com.example.sample.MainActivity$PlaceholderFragment" >

    <android.support.v4.view.ViewPager
        xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:app="http://schemas.android.com/apk/res-auto"
        android:id="@+id/image_pager"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

</RelativeLayout>
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent" >

    <ImageView
        android:id="@+id/background"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

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

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_weight="1.0"
            android:orientation="horizontal" >

            <Button
                android:id="@+id/button1"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:layout_weight="1.0"
                android:alpha=".5"
                android:background="@android:color/white"
                android:text="Button" />

            <Button
                android:id="@+id/button2"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:layout_weight="1.0"
                android:alpha=".5"
                android:background="@android:color/holo_green_light"
                android:text="Button" />
        </LinearLayout>

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_weight="1.0"
            android:orientation="horizontal" >

            <Button
                android:id="@+id/button3"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:layout_weight="1.0"
                android:alpha=".5"
                android:background="@android:color/holo_blue_light"
                android:text="Button" />

            <Button
                android:id="@+id/button4"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:layout_weight="1.0"
                android:alpha=".5"
                android:background="@android:color/holo_red_light"
                android:text="Button" />
        </LinearLayout>
    </LinearLayout>

</FrameLayout>